Auto-loading vendor files (or any other file)

Published on and tagged with cakephp  php  tip  vendor

If you use classes which do not fit into CakePHP’s structure (i.e. they are no components, helpers, etc.), you have to import those classes manually with App::import(‘Vendor’, ‘ClassName’), at least if your classes are in the “vendors” folder. This means, every time you want to use such a class, you first have to import it before you can use it. And that’s a bit of a pain ;-)

Fortunately, PHP5 provides a solution for this “problem”: auto-loading. The explanation from the manual: “You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.”

In CakePHP a good place for this function is app/config/bootstrap.php. The function to auto-load vendor files looks like:

function __autoload($className) {
    App::import('Vendor', $className);
}

If you want to use a custom function or a method of a class, you simply have to register your auto-load implementation. The example from above realized with a static method looks like:

class AutoLoader {
    public static function load($className) {
        App::import('Vendor', $className);
    }
}

spl_autoload_register(array('AutoLoader', 'load'));

You can find more information about auto-loading in the PHP manual: Autoloading objects and spl_autoload_register.

Happy baking!

5 comments baked

  • Juan Basso

    I think that this feature can implemented in Cake core. Put the function on basics.php or implements a method in App class and use spl_autoload_register to call.
    Maybe, if load fail, can find a Model, Component, …

  • cakebaker

    @Juan: Thanks for your comment!

    I don’t think this will make it in the core any time soon, because Cake 1.2 still supports PHP4 and this is a PHP5 feature… But maybe the cake devs will make use of this feature in a later version of cake…

  • Автоматическая загрузка внешних библиотек - Программируем на CakePHP

    […] записи Auto-loading vendor files (or any other file) с блога […]

  • David Thalmann

    SPL supports nice classes and interfaces for searching/iterating (<- *hint* ^^) through folders, together with autoload a very powerful feature of php5. But in large projects with deep folder structure is searching for classes slowing down everything. Possible solution: precached/automatic generated class list!

    <?php
    /**
     * Loads classes, search (recursively) in $path
     *
     * @todo speedup this function with precached filelist
     *
     * @param string $class
     * @param string $path
     * @param bool $recursive
     */
    function autoloader($class, $path, $recursive = true) {
    	$dir = new RecursiveDirectoryIterator($path);
    	$dir_r = array();
    
    	foreach($dir as $file) {
    		if(!$file->isDir() && $file == Inflector::underscore($class))
    			require_once($class);
    		elseif($file->isDir() && $recursive && substr($file->getFilename(), 0, 1) != '.') // prevent loading folders like .svn
    			$dir_r[] = $file;
    	}
    
    	if($recursive)
    		foreach($dir_r as $dirs)
    			autoloader($class, $dirs);
    }
    
    /**
     * autoload helper function
     *
     * @param string $class
     */
    function core_autoloader($class) {
    	$list = array(
    		'Inflector'			=> LIB.'inflector.php',
    		'AnotherClass'	=> LIB.'anotherClass.php'
    		/* more here */
    	);
    
    	if(array_key_exists($class, $list))
    		require_once($list[$class]);
    	else
    		autoloader($class, CORE);
    }
    
    /**
     * Initialize the spl_autoload functions
     * - first activate the autoload function, no magic __autoload() method =)
     * - speed up searching with dropping the .inc extension and set .php as main extension
     * - register our fast autoload function
     */
    spl_autoload_register(null);
    spl_autoload_extensions('.php');
    spl_autoload_register('core_autoloader');
    
    ?>

    Hope could help sb with this.

  • cakebaker

    @David: Thanks for sharing this code! And yes, the SPL provides some nice things which, unfortunately, are not so well-known…

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License