Load a class with Zend_Loader_Autoloader by name | without namespaces or prefixes

The web is filled with examples of using Zend Autoloading using the fancy namespace and prefix features of the Zend_Loader_Autoloader, but what if all you want to do is auto load a class based on its name corresponding to a file name?

//For example what if you want
$instance = Instance();
//to automatically include the class from /path/to/apache/webroot/library/Instance.php, what if you want that?

While using prefixes to divide your libraries up into different groups speeds up access times, this is not useful if your retroactively implementing auto loading. Using the include path is a little slow but its supper simple to implement.

In Bootstrap.php add the following code:

//configure Zend Auto Loader
$autoloader = Zend_Loader_Autoloader::getInstance();
//sets the auto loader to use the include path
$autoloader->setFallbackAutoloader(true);

//that is it unless you need to add your directory to the include path
//so that the auto loader will search for your class in that directory

//create current include path
$pathArray = explode(DIRECTORY_SEPARATOR, __FILE__);
//remove Bootstrap.php
array_pop($pathArray);
//remove parent directory
array_pop($pathArray);
//create /path/to/apache/webroot
$path = implode(DIRECTORY_SEPARATOR,$pathArray);
// add library to web root to make /path/to/apache/webroot/library/
path .= DIRECTORY_SEPARATOR.'library'.DIRECTORY_SEPARATOR;
//get list of current include paths
$includePathsArray = explode(PATH_SEPARATOR, get_include_path());
if (includePathsArray == NULL){
$includePathsArray = array();
}
//add new include path
array_push($includePathsArray, $path);
//make sure there are not any duplicate paths
$includePathsArray = array_unique($includePathsArray);
//create include path string and rewrite the list of include directories
set_include_path(implode(PATH_SEPARATOR, $includePathsArray));

Now the zend autoloader will look for file names that resemble your class names by looking in the list of include directories including the library directory that we added.

comments powered by Disqus