Autoloading Zend Framework 2 packages with the StandardAutoloader

心不动则不痛 提交于 2019-12-23 05:36:08

问题


I was previously using a downloaded version of Zend Framework 2 and was basically able to do something like this:

// Set include paths (add Zend to the path)
set_include_path(get_include_path() . PATH_SEPARATOR . $__CONFIG['zendPath']);

// Setup the Zend Autoloader
require_once('library\Zend\Loader\StandardAutoloader.php');

$autoLoader = new StandardAutoloader(array(
    'namespaces' => array(
        'Zend' => $__CONFIG['zendPath'] . '/library/Zend'
    )
));

This works because all Zend packages are inside the library folder. I now wanted to use composer to load only the Zend packages I need. The problem I'm running into is that the packages get arranged in the following way:

zendframework/zend-cache/Zend/...
zendframework/zend-loader/Zend/...
zendframework/zend-validator/Zend/...
etc.

I tried having separate namespace declarations in the StandardAutoloader like this:

$autoLoader = new StandardAutoloader(array(
    'namespaces' => array(
        'Zend\Cache' => $__CONFIG['zendPath'] . '/library/zend-cache/Zend/Cache',
        'Zend\Loader' => $__CONFIG['zendPath'] . '/library/zend-loader/Zend/Loader',
        'Zend\Validator' => $__CONFIG['zendPath'] . '/library/zend-validator/Zend/Validator'
    )
));

That doesn't work. Am assuming the namespace probably can't have the backslashes in it? is there any way to make this work? Preferably without having to define each individual package.


回答1:


You just have to fix the paths:

$libs = $__CONFIG['zendPath'];
$autoLoader = new StandardAutoloader(array(
    'namespaces' => array(
        'Zend\Cache' => $libs . '/library/zend-cache/Zend',
        'Zend\Loader' => $libs . '/library/zend-loader/Zend',
        'Zend\Validator' => $libs . '/library/zend-validator/Zend',
    )
));

That should do the trick (it's un-tested, so I'm not sure about the trailing Zend




回答2:


Let it autoload Zend for you:

$autoLoader = new StandardAutoloader(array(
    'autoregister_zf' => true, // Auto load Zend Namespace..
    'namespaces' => array(
         // extra namespaces
    )
));


来源:https://stackoverflow.com/questions/15162157/autoloading-zend-framework-2-packages-with-the-standardautoloader

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