Search code examples
zend-frameworknamespaceszend-autoloader

Zend Autoloading models issue


Zend framework. I want to autoload my models classes inside models folder, from within bootstrap class. These models doesnt actually use any namespace (so I have Ex. User.php file's class named User and so on..).

If I understood correctly I should use the Zend_Loader_Autoloader_Resource and I tried:

function _initLoaderResource() 
{         
    $resourceLoader = new Zend_Loader_Autoloader_Resource(array(                 
    'basePath'  => APPLICATION_PATH,//points to the "application" path where resides "models" folder
    'namespace' =>''       
    ));         

    $resourceLoader->addResourceType('models', 'models/');

} 

And I receive following 'Zend_Loader_Exception' message:

'Initial definition of a resource type must include a namespace' 

My questions are:

  • Is this the right way to autoload models?
  • How should I manage resource code that doesn't follow Zend Framework coding standard?

Solution

  • Actually you probably don't want to use the resource autoloader for this, since (as you've discovered) it requires a namespace. The standard autoloader (which loads models from the include path) has an option setFallbackAutoloader which tells ZF that that autoloader should be used for any class not matching a namespace covered by another. So all you need to do is ensure your models directory is on the include path and set this option to true.

    You are probably already using the standard autoloader for loading the Zend classes, so you'll probably want to modify your application.ini file to add your model directory to the include path, and then set the fallback option either in application.ini or in your Bootstrap class:

    protected function _initAutoloader()
    {
        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->setFallbackAutoloader(true);
    
        return $autoloader;
    }