Zend框架中的自动加载

Zend框架中的自动加载

本文介绍了Zend框架中的自动加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在模块路径上的自定义目录中自动加载类.我的应用程序的结构如下所示

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

我有两个自定义目录"api"和"elements",当我实例化这两个类的对象时,我收到了错误消息:未找到致命错误类Admin_Api_Core".我尝试使用registerNamespace,但是根本无法正常工作

i have two custom directory, 'api' and 'elements', when i instantiated an object of that two class i have 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_');

推荐答案

您可以在Module_Bootstrap内部配置自动加载功能(与Benjamin Cremer的答案几乎相同,但基于模块).为此,请在/modules/admin文件夹中创建具有以下内容的文件Bootstrap.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;
    }

}

之后,您将可以实例化Admin_Api_Core等类(您应指定所有resoursTypes).如果您有许多模块,则可以为所有模块创建此类引导程序.

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.

这篇关于Zend框架中的自动加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:08