Search code examples
phpzend-frameworkautoloader

Use Zend_Autoloader for Models


does someone knows how to use the "new" Zend Autoloader to Load Models ? In the Moment my Configuration looks like this :

application.ini

# Autoloader Namespace
autoloadernamespaces.0 = "Sl_"

Bootstrap.php

   /**
     * Start Autoloader
     *
     * @access protected
     * @return Zend_Application_Module_Autoloader
     */
    protected function _initAutoload()
    {
        $autoloader = new Zend_Application_Module_Autoloader(array(
            'namespace' => 'Sl_',
            'basePath'  => dirname(__FILE__),
        ));

        return $autoloader;
    } 

So when I place a Model in /Models/User.php with

class Sl_Model_User{}

and create an new object , everything works like designed. But how can i use the Autoloader to load a Model placed in /Models/Dao/UserDB.php ?

class Dao_UserDB{}

Solution

  • Check the documentation on the Resource_Autoloader (its purpose is to load resources that reside in the models directory or elsewhere - i.e outside the /library folder).

    "Resource autoloaders are intended to manage namespaced library code that follow Zend Framework coding standard guidelines, but which do not have a 1:1 mapping between the class name and the directory structure. Their primary purpose is to facilitate autoloading application resource code, such as application-specific models, forms, and ACLs.

    Resource autoloaders register with the autoloader on instantiation, with the namespace to which they are associated. This allows you to easily namespace code in specific directories, and still reap the benefits of autoloading."

    path/to/some/directory/
        acls/
             Site.php
        forms/
            Login.php
        models/
            User.php
    
    
    $resourceLoader = new Zend_Loader_Autoloader_Resource(array(
    'basePath'  => 'path/to/some/directory',
    'namespace' => 'My',
    

    ));

    $resourceLoader->addResourceTypes(array(
    'acl' => array(
        'path'      => 'acls/',
        'namespace' => 'Acl',
    ),
    'form' => array(
        'path'      => 'forms/',
        'namespace' => 'Form',
    ),
    'model' => array(
        'path'      => 'models/',
    ),
    

    ));

    Try this in your boostrap file:

    protected function _initLoaderResource()
    {
        $resourceLoader = new Zend_Loader_Autoloader_Resource(array(
            'basePath'  => 'your_doc_root' . '/application',
            'namespace' => 'MyNamespace'
        ));
        $resourceLoader->addResourceTypes(array(
            'model' => array(
                'namespace' => 'Model',
                'path'      => 'models'
            )
        ));
    }