Suppose I have the following file structure in 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 index.php , I include the file autoload.php
<?php
include_once 'autoload.php';
// resto do código
My autoload.php file 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 witchcraft that I do not 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 the recognition is the same. It works!
Well, I have a closure autoload that works, but how does this closure work? How does PHP's autoloading recognize classes within folders, even though I have indicated only the project root?
PHP is going inside the folders and recognizing the classes, how is this possible?
The big detail of this is that if the MainModel.php file is not inside a MainModel folder (with the same file name) the autoload does not work.
Another curious thing is that the namespace have to indicate the path of the file to the class from the root Models\MainModel
, then I declare the class.
I do not want to know how to use autoload, because this I already got, but rather how it works, because I'm using something I do not know how it works.
My question is completely different from that of moderates in the site: see "duplicate possible" / a>