- Published on
Zend Framework Autoload Classes
- Authors
- Name
- Frank
I wanted to add another library of classes to a Zend Framework project and autoload them, I created a folder called application/vendors/ to hold vendor libraries in seperate folders of their own. For example, using some CURL classes from Sem Labs, these classes would live in the application/vendors/semlabs/ folder.
I renamed the classes to match the Zend Framework class naming structure for autoloading:
class Vendors_Semlabs_CurlRequest extends Vendors_Semlabs_Curl
class Vendors_Semlabs_Curl
In a model I wanted to simply create that class and have it autoloaded automagically without having to require the class file or anything like that:
$curlRequest = new Vendors_Semlabs_CurlRequest();
Getting this to work as intended was a bit of mission, ended up with the code for autoloading vendor classes in bootstrap in the _initAutoload() method:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
/**
* Get the autoloader the base path for the module (application),
* add a new resource autoloader for the vendors folder to include vendor classes
*
* @return void
*/
protected function _initAutoload()
{
$autoloader = Zend_Loader_Autoloader::getInstance();
$r = new ReflectionClass($this);
$path = $r->getFileName();
$vendorsAutoloader = new Zend_Loader_Autoloader_Resource(array(
'namespace' => 'Vendors',
'basePath' => dirname($path).'/vendors',
));
$vendorsAutoloader->addResourceType('semlabs', 'Semlabs/', 'Semlabs');
$autoloader->pushAutoloader($vendorsAutoloader);
}
}