In registry pattern we just create objects that we need for example:
public function createAndStoreObject( $object, $key )
{
require_once( $object . '.class.php' );
$this->objects[ $key ] = new $object( $this );
}
And then access it via its key.
In autoloader we do something like this:
<?php
class autoloader {
public static function moduleautoloader($class) {
$path = $_SERVER['DOCUMENT_ROOT'] . "/modules/{$class}.php";
if (is_readable($path)) {
require $path;
}
}
public static function daoautoloader($class) {
$path = $_SERVER['DOCUMENT_ROOT'] . "/dataobjects/{$class}.php";
if (is_readable($path))
require $path;
}
public static function includesautoloader($class) {
$path = $_SERVER['DOCUMENT_ROOT'] . "/includes/{$class}.php";
if (is_readable($path))
require $path;
}
}
spl_autoload_register('autoloader::includesautoloader');
spl_autoload_register('autoloader::daoautoloader');
spl_autoload_register('autoloader::moduleautoloader');
?>
And then it’s used as below:
When we want to create an object it should go through includes, modules OR dataobjects folder to find the class and then if it exists, object should be created.
For a huge application do we have to go though registry approach or there are some benefit using autoloader here?
Using
require_onceis arguably faster than having it automatically load, especially when it’s only called once.But having an autoloader frees you from explicitly loading all the classes you need, it will just be there. And it’s on-demand, so if you decide to change your code and no longer need a particular class you don’t have to remember to stop including the class definition file.
Btw, based on your code I would recommend putting them into one auto loader function:
This would perform somewhat better than having three separate functions.
To make it more efficient you could consider using namespaces; they form a logic directory structure and make the auto loader simpler to make.