将设置包含在模块类中

时间:2013-08-20 19:19:19

标签: zend-framework zend-framework2

我的module.config.php文件得到以下摘录:

return array(
    'service_manager' => array(
        'aliases' => array(
            'Util\Dao\Factory' => 'modelFactory',
        ),
        'factories' => array(
            'modelFactory' => function($sm) {
                $dbAdapter = $sm->get('Doctrine\ORM\EntityManager');
                return new \Util\Dao\Factory($dbAdapter);
            },
        )
    ),
    'doctrine' => array(
        'driver' => array(
            'application_entities' => array(
                'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
                'cache' => 'array',
                'paths' => array(
                    __DIR__ . '/../src/Application/Model'
                ),
            ),
            'orm_default' => array(
                'drivers' => array(
                    'Application\Model' => 'application_entities'
                )
            ),
        ),
    ),

如何将块“doctrine”放在模块类中?

1 个答案:

答案 0 :(得分:0)

嗯,这其实很简单。可能你的Module类有方法getConfig()。该方法通常会加载moduleName/config/module.config.php

因此,无论您使用何种函数,只需调用getConfig() - 方法即可。这是纯粹的基本php;)

//Module class
public function doSomethingAwesome() {
    $moduleConfig   = $this->getConfig();
    $doctrineConfig = isset($moduleConfig['doctrine'])
                        ? $moduleConfig['doctrine']
                        : array('doctrine-config-not-initialized');
}

但是,您需要注意这只包括您的模块配置。如果您需要访问合并配置,则需要在onBootstrap() - 方法中执行此操作。这将是这样做的:

//Module class
public function onBootstrap(MvcEvent $mvcEvent)
{
    $application   = $mvcEvent->getApplication();
    $serviceLocator = $application->getServiceLocator();
    $mergedConfig   = $serviceLocator->get('config');
    $doctrineConfig = isset($mergedConfig['doctrine']) 
                        ? $mergedConfig['doctrine'] 
                        : array('doctrine-config-not-initialized');
}

如果您附加某些事件,这种方式类似......