开发者

Autoloading in zend framework

开发者 https://www.devze.com 2023-03-11 04:20 出处:网络
how to autoload a class in custom directory on module path. My application\'s structure is like below

how to autoload a class in custom directory on module path. My application's structure is like below

application
|_ modules
   |_admin
     |_api
     | |_Core.php
     |_elements
       |_Dialog.php

i have two custom directory, 'api' and 'elements', when i instantiated an object of that two class i hav开发者_开发问答e received error message: 'Fatal error class Admin_Api_Core is not found'. I try with registerNamespace but it not work at all

Zend_Loader_Autoloader::getInstance()->registerNamespace('Admin_');


Have a look at ZFs Resource Autoloaders.

Add the following to your Bootstrap.php

protected function _resourceLoader()
{
    $resourceLoader = new Zend_Loader_Autoloader_Resource(array(
        'basePath'      => 'APPLICATION_PATH',
        'namespace'     => '',
        'resourceTypes' => array(
            'acl' => array(
                'path'      => 'api/',
                'namespace' => 'Acl',
            ),
            'form' => array(
                'path'      => 'elements/',
                'namespace' => 'Element',
            ),
        ),
    ));
}

Api_Core loads APPLICATION_PATH . '/api/Core.php
Element_Core loads APPLICATION_PATH . '/elements/Core.php
Admin_Api_Core loads APPLICATION_PATH . '/modules/admin/api/Core.php
Admin_Element_Core loads APPLICATION_PATH . '/modules/admin/elements/Core.php


You can configure autoloading inside your Module_Bootstrap (almost same approach as in Benjamin Cremer's answer but module based). To do it - create file Bootstrap.php in /modules/admin folder with the following content:

class Admin_Bootstrap extends Zend_Application_Module_Bootstrap
{

    protected function _initAutoload()
    {
        $resourceLoader = new Zend_Loader_Autoloader_Resource(array(
            'basePath'      => realpath(dirname(__FILE__)),
            'namespace'     => 'Admin',
            'resourceTypes' => array(
                'api' => array(
                    'path'      => 'api/',
                    'namespace' => 'Api'
                )
            )
        ));

        $autoloader = new Zend_Application_Module_Autoloader(array(
            'namespace' => 'Admin',
            'basePath'  => dirname(__FILE__),
            'resourceloader' => $resourceLoader
        ));
        return $autoloader;
    }

}

After that you'll be able to instantiate class Admin_Api_Core etc. (you should specify all resoursTypes). If you have many modules, you can create such bootstraps for all of them.

0

精彩评论

暂无评论...
验证码 换一张
取 消