I am just starting to look at Zend Framework 2 (and am new to ZF in general), and in the user guide, they are using autoloading when adding a new module. However, I find the explanation to be quite challenging for a rookie. They are adding a Module.php
file within the module directory, which among others contains the following code:
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
Now I did some digging around to try and figure out what this autoloading is all about. As far as I understand, the autoloading uses spl_autoload_register()
and is a way to avoid having require_once()
everywhere in the code. So, when trying to use a class that is not defined, the autoload()
method that was registered will be run, which simply does an array lookup and includes the file like below if it was added.
// Zend/Loader/ClassMapAutoloader.php
public function autoload($class)
{
if (isset($this->map[$class])) {
require_once $this->map[$class];
}
}
This seems clever due to performance. I hope what I just wrote is correct. Based on this, I am trying to figure out what is going on in getAutoloaderConfig()
from the first code snippet, but I am quite confused. It seems as if the array that is returned by this method is used for AutoloaderFactory::factory()
, but I am not sure for what purpose. Instantiating autoloaders with options it seems, but exactly what that does, I am not sure. I guess the second entry of the array specifies where to find the source files for the module's namespace - at least that would be my guess. The first entry I am, however, not sure about. In the user guide, it says the following:
As we are in development, we don’t need to load files via the classmap, so we provide an empty array for the classmap autoloader.
The file just returns an empty array. I am not sure what the purpose of this ClassMapAutoloader.
Sorry if my point is unclear; basically I am trying to figure out what is happening in getAutoloaderConfig()
and what mymodule/autoload_classmap.php
is used for. If someone could shed some light on this, that would be much appreciated!