SPL autoloading in PHP
In php5 we have a fabulous new feature, autoloading Objects. This function load dynamically classes.Before this magic function, we had to include all needed files before using an object.
How it works ? Very simple :
function __autoload($class) { if(is_file($class . '.php')){ require_once $class.'.php'; }else{ printf("Error when trying to load %s", $class); } } $mmpObj = new MmpClass();
In php >= 5.1.2 a new SPL function upgrade this function. How ? You can declare multiple autoload functions. You can register as much autoload functions as you want with the spl_autoload_register function.
A small example :
We have an application with source classes in /kernel. We have specific classes in a different directory : /apps/lib. The autoload functions are defined in a /config/config.ini.php file. In the /kernel we have differents subdirectory.
spl_autoload_register(null,false); function appsLibLoader($classLib) { $classLib = strtolower($classLib); if(is_file(__DIR__."/../apps/lib/lib.".$classLib.".php")){ require(__DIR__."/../apps/lib/lib.".$classLib.".php"); }else{ echo "ERROR during Loading class::".$classLib; } }function kernelLoader($classKernel) { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../kernel/",RecursiveDirectoryIterator::KEY_AS_FILENAME),RecursiveIteratorIterator::SELF_FIRST); foreach ($iterator as $entry){ if($entry->isFile() && strtolower($classKernel) == strtolower(basename($iterator->current(),".php"))){ require($iterator->getPathname()); } } } spl_autoload_register('appsLibLoader',false); spl_autoload_register('kernelLoader',false);


5 Comments
Jump to comment form | comments rss [?] | trackback uri [?]