Zend Framework 2 including custom library

随声附和 提交于 2019-12-06 05:22:25
Rob Allen

You need to configure the StandardAutoloader to load your library classes. The easiest way is to modify the Application module's Module::getAutoloaderConfig() method so that it looks something like this:

public function getAutoloaderConfig()
{
    return array(
        'Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
                __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
            ),
            'prefixes' => array(
                'CL' => 'c:\\Workspaces\\Custom library/CL',
                'D' => 'c:\\Workspaces\\Custom library 2/D',
            ),
        ),
    );
}

I've added a prefixes key and then listed the prefix name and where to find it on disk. The Standard Autoloader documentation has more details.

If you are working with a Zend Skeleton Application you may also simply add these namespaces to your init_autoloader.php file.

The namespace of your class is Main\Controller. If you instanciate a new class here new CL_Res_Chain_Mutable() php will load it relative to the current namespace Main\Controller\CL_Res_Chain_Mutable. Your class is not a namespaced class so you need to load it from the root. Just put a \ in front new \CL_Res_Chain_Mutable().

By default your application will be using the Standard Autloader (PSR-0). This will find your files based on a namespaces, and a naming convension used by ZF2. ZF2 will allow you to register multiple Autoloaders, so you can use different strategies, which is what you will need to do, here's an example:

Module.php

/**
 * Get autoloader config
 * 
 * @return array
 */
public function getAutoloaderConfig()
{
    return array(
        'Zend\Loader\ClassMapAutoloader' => array(
            // File containing class map key/value pairs
            __DIR__ . '/library/autoloader_classmap.php',
            // Or provide an array with the class map instead...
            array( 
                'Application\Bootstrap' => __DIR__ . '/application/Bootstrap.php',
                'CL_Res_Chain_Mutable'  => __DIR__ . '/library/pathhere/Mutable.php',
            ),
        ),
        'Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
                __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
            ),
        ),
    );
}

This setup will use tell ZF2 to check the class map first, if it can't find what it's looking for it will revert to the standard autoloader.

http://framework.zend.com/manual/2.0/en/modules/zend.loader.class-map-autoloader.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!