Access to module config in Zend Framework 2

前端 未结 8 2135
清酒与你
清酒与你 2021-01-30 21:05

How I can get access to my module config from the controller?

8条回答
  •  旧时难觅i
    2021-01-30 21:43

    What exactly do you want to do in your controller with the module configuration? Is it something that can't be done by having the DI container inject a fully configured object into your controller instead?

    For example, Rob Allen's Getting Started with Zend Framework 2 gives this example of injecting a configured Zend\Db\Table instance into a controller:

    return array(
    'di' => array(
        'instance' => array(
            'alias' => array(
                'album' => 'Album\Controller\AlbumController',
            ),
            'Album\Controller\AlbumController' => array(
                'parameters' => array(
                    'albumTable' => 'Album\Model\AlbumTable',
                ),
            ),
            'Album\Model\AlbumTable' => array(
                'parameters' => array(
                    'config' => 'Zend\Db\Adapter\Mysqli',
            )),
            'Zend\Db\Adapter\Mysqli' => array(
                'parameters' => array(
                    'config' => array(
                        'host' => 'localhost',
                        'username' => 'rob',
                        'password' => '123456',
                        'dbname' => 'zf2tutorial',
                    ),
                ),
            ),
            ...
    

    If you need to do additional initialization after the application has been fully bootstrapped, you could attach an init method to the bootstrap event, in your Module class. A blog post by Matthew Weier O'Phinney gives this example:

    use Zend\EventManager\StaticEventManager,
    Zend\Module\Manager as ModuleManager
    
    class Module
    {
        public function init(ModuleManager $manager)
        {
            $events = StaticEventManager::getInstance();
            $events->attach('bootstrap', 'bootstrap', array($this, 'doMoarInit'));
        }
    
        public function doMoarInit($e)
        {
            $application = $e->getParam('application');
            $modules     = $e->getParam('modules');
    
            $locator = $application->getLocator();
            $router  = $application->getRouter();
            $config  = $modules->getMergedConfig();
    
            // do something with the above!
        }
    }
    

    Would either of these approaches do the trick?

提交回复
热议问题