How to include third party lib in Zend Framework 2

亡梦爱人 提交于 2019-12-08 13:30:58

问题


I'm migrating application from ZF1 to ZF2. I have a controller depends on third party lib 'Solarium'.

namespace Stock\Controller;
class BaseController extends AbstractActionController
{
    protected function indexAction()
    {
        require_once('Solarium/Autoloader.php');
        Solarium_Autoloader::register();

The 'Solarium' exists under 'vendor', and in 'init_autoloader.php' I have:

set_include_path(implode(PATH_SEPARATOR, array(
    realpath('vendor')
)));

But, when I viewing the page, there's an error:

Fatal error: Class 'Stock\Controller\Solarium_Autoloader' not found in ...

I tried to add trace in 'StandardAutoloader.php' and found StandardAutoloader.autoload('Stock\Controller\Solarium_Autoloader') is called on runtime.

I want to know how this happens and how to fix it. Thanks.


回答1:


As Aydin Hassan wrote in his comment, the easiest way to make this work is by using Composer. First, edit your composer.json file within your project's root directory to look something like this:

"require": {
    "php": ">=5.3.3",
    "zendframework/zendframework": "2.*",
    "solarium/solarium": ">=2.4.0"
}

If you are using the Zend Skeleton Application, then you will also have Composer itself in your project's root directory (composer.phar). In that case, you can do like this:

cd /path/to/project && php composer.phar install solarium/solarium

Or

cd /path/to/project && php composer.phar install

Otherwise just have Composer available everywhere in your command line. By doing like above, Composer will take care of autoloading for you. Within your controller, you should then not worry about including the file as this happens automatically for you with spl_autoload_register. You just have to use the namespace. You can use either of these two approaches:

namespace Stock\Controller;

use Solarium\Autoloader;

class BaseController extends AbstractActionController
{
    protected function indexAction()
    {
        Autoloader::register();
    }
}

Or

namespace Stock\Controller;

class BaseController extends AbstractActionController
{
    protected function indexAction()
    {
        \Solarium\Autoloader::register();
    }
}


来源:https://stackoverflow.com/questions/16000465/how-to-include-third-party-lib-in-zend-framework-2

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