Search code examples
phpzend-frameworkzend-framework2zend-db

How to load Zend 2 classes on autoloader


Previously, i am using zend 1.x. I am able to autoload zend classes using the below code.

// autoload class from Zend Lib
require_once ABSPATH.'/classes/Zend/Loader/Autoloader.php'; 
$loader = Zend_Loader_Autoloader::getInstance();    
 try{
// database connection      
$dbo = Zend_Db::factory('pdo_mysql', array( 
        'host'     => DB_HOST, 
        'username' => DB_USER, 
        'password' => DB_PW, 
        'dbname'   => DB_PREFIX.DB_NAME
    )); 
$dbo->getConnection();
// save database adapter for easy usage in other classes
Zend_Db_Table::setDefaultAdapter($dbo);
Zend_Registry::set('db', $dbo);

}catch(Zend_Db_Adapter_Exception $e){
print $e;
 //header("Location: http://www.google.com/error/");
}

I am upgrading to zend 2 as the classes might be better. May i know how do i autoload them?


Solution

  • If you are just using ZF2 as a standalone library without employing the full MVC framework, then autoloading is fairly straightforward:

    1. Make sure that the Zend directory is on your php include_path.
    2. Push an autoloader using spl_autoload_register

    The following is essentially what Zend\Loader\StandardAutoloader::loadClass() does when functioning as a fallback autloader:

    spl_autoload_register(function($class) {
        $f = stream_resolve_include_path(str_replace('\\', '/', $class) . '.php');
        if ($f !== false) {
            return include $f;
        }
        return false;
    });
    

    This would use the PSR-1 autloading mechanism for all classes, not just the Zend classes.

    Alternatively, you could just do the following:

    require_once 'Zend/Loader/StandardAutoloader.php';
    $autoloader = new Zend\Loader\StandardAutoloader(array(
        'fallback_autoloader' => true,
    ));
    $autoloader->register();
    

    As above, this will apply PSR-1 autoloading to all classes. If you want this mechanism for the Zend classes only, then pass 'fallback_autoloader' => false.