3
Suppose I have the following file structure at the root of my site:
index.php
autoload.php
----| /Models
--------| /MainModel
------------| MainModel.php
----| /Controllers
--------| /MainController
------------| MainController.php
Suppose there is a method in Mainmodel.php called mainMethod() as follows:
<?php namespace Models\MainModel;
class MainModel
{
public function mainMethod()
{
return json_encode(array('mensagem' => 'Tudo funcionando por aqui'));
}
}
In the index php., i include the file autoload.php
<?php
include_once 'autoload.php';
// resto do código
My file autoload.php has the following code:
spl_autoload_register(function ($class) {
$prefix = '';
$base_dir = __DIR__.'/';
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
return;
}
$relative_class = substr($class, $len);
$file = $base_dir.str_replace('\\', '/', $relative_class).'.php';
if (file_exists($file)) {
require $file;
}
});
Now comes the witchcraft that I don’t understand how it works. If I do:
<?php
include_once 'autoload.php';
$obj = new Models\MainModel\MainModel;
echo $obj->mainMethod();
// Output: {"mensagem": "Tudo funcionando por aqui"}
Even if I indicate the classes of controllers recognition is the same. It works!
Well, I have a closure autoload that works, but like this closure works? How the self-loading PHP recognizes the classes inside folders, even though I only indicated the project root?
PHP is going there inside the folders and recognizing the classes, as this is possible?
The great detail of it all is that if the file Mainmodel.php is not inside a folder Mainmodel (with the same file name) autoload doesn’t work.
Another curious thing is that the namespace have to indicate the file path to the class from the root Models\MainModel
, then I declare the class.
I don’t want to know how to use autoload, because that I already got, but rather how it works, because I’m using something I don’t know how it works.
My question is completely different from the one chosen by the moderates of the site: see "possible duplicate"
I already gave +1 to the two answers and used them as a reference. I changed the details of the functions
is_file()
andfiles_exists()
and I’m using include. But you could explain more how autoload "pulls" the file classes and why a specific file structure is needed (or not, because in my case it only worked with a specific structure)?– Not The Real Hemingway
@Nottherealhemingway edited the answer and detailed all points of implementation, I hope it helps
– Guilherme Nascimento
Great question and great answer. Congratulations to both of you. : D
– Antonio Alexandre
Perfect! Thank you, @Guilhermenascimento. You saved my arse Twice Today
– Not The Real Hemingway
@Nottherealhemingway added two explanations to his specific doubts at the end of the answer.
– Guilherme Nascimento