ZfcTwig 未加载配置并在 bootstrap 中失败

ZfcTwig is not loading config and fails in bootstrap

您好,我对 ZF2 比较陌生,所以这可能是我犯的一个非常简单的错误。

问题

加载 ZfcTwig 模块时出现异常

Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Twig_Environment' in /www/ZendFramework2/library/Zend/ServiceManager/ServiceManager.php on line 555

这个异常是在ZfcTwig\Module.phponBootstrap函数中抛出的:

<?php
class Module implements
  BootstrapListenerInterface,
  ConfigProviderInterface
{
  public function onBootstrap(EventInterface $e)
  { 
    /** @var \Zend\Mvc\MvcEvent $e*/
    $application    = $e->getApplication();
    $serviceManager = $application->getServiceManager();
    $environment    = $serviceManager->get('Twig_Environment'); // throws the exception
    //...
  }
  public function getConfig(){ return [/*...*/]; } // never called
}

我不明白为什么在加载配置之前调用 bootstrap。 'Twig_Environment' 服务在 ZfcTwig 模块的配置中配置,但在调用 onBootstrap 时该配置尚未加载。

设置

ZF2 加载程序通过 ZF2_PATH 环境变量。不使用作曲家自动加载器。

application.config.php 我设置了一个额外的模块路径 '/global/vendor' 到我的可重用模块的系统范围存储库。我没有使用项目本地供应商文件夹。

来自 '/global/vendor/ZfcTwig' 我正在加载模块 ZfcTwig (link) 以获得 ZF2 中的 Twig 模板引擎支持。

由于这依赖于 twig 库,所以我将 twig 库放入 '/global/vendor/twig'

为了启用 ZfcTwig 模块和 twig 库的自动加载 类 我通过实施 AutoloaderProviderInterface 并为 twig 和 ZfcTwig 添加配置更改了 ZfcTwig Module.php。

<?php
class Module implements
    BootstrapListenerInterface,
    AutoloaderProviderInterface,
    ConfigProviderInterface
{
    /**
     * Autoloading the twig library and this modules classes
     * @return array
     */
    public function getAutoloaderConfig()
    {
        $pathToTwigLib = dirname(dirname(dirname(__DIR__))) . '/twig/twig/lib/Twig';
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__,
                ),
                'prefixes' => array(
                    'Twig_' => $pathToTwigLib,
                ),
            ),
        );
    }

application.config.php 我正在加载模块 ['Application','twig','ZfcTwig']

twig 的自动加载正在运行(至少我可以使用 new 在 ZfcTwig 和其他控制器的 bootstrap 中实例化 Twig_Environment

启用配置缓存

问题正是我想知道的地方。在引导完成之前需要加载配置。然而,这正是 ZF2 所做的,除非像我一样启用了配置缓存。

<?php
// config/applicaiton.config.php
return array(
  'module_listener_options' => array(
    // this prevents the call to getConfig on Modules
    // that implement the ConfigProviderInterface
    // default: false
    'config_cache_enabled' => true, 
  )
);