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!
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, …
@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…
[…] запиÑи Auto-loading vendor files (or any other file) Ñ Ð±Ð»Ð¾Ð³Ð° […]
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!
Hope could help sb with this.
@David: Thanks for sharing this code! And yes, the SPL provides some nice things which, unfortunately, are not so well-known…