Access config global in Zend Framework 2

2019-05-29 00:20发布

问题:

I would like to access to my global configs (config/{,*.}{global,local}.php) located in my personal libraries (in the vendor directory). But despite my search in the web, I did not succeed to achieve this.

I know how to access the config file of a module :

\MyModule\Module::getConfig()

I know how to access the global configurations from a controller :

$this->getServiceLocator()->get('config');

But how to access these from a file inside the vendor directory ? My libraries do not extend anything, it may be the root of the problem ? Can I use a static method to access these ?

Thanks.

回答1:

You can get it through the serviceManager. In controller:

$config = $this->getServiceLocator()->get('Config');

Otherwise same way, just you need service Manager, for eaxmple in Module.php:

  public function getConfig()
  {
    return include __DIR__ . '/config/module.config.php';
  }

  public function getServiceConfig()
  {
    return array(
        'factories' => array(
            'mail.transport' =>  function($sm) {
                $config = $sm->get('Config');

                 switch($config['mail']['transport']['type']){
                ..................


回答2:

easy way to do this. not only in module but anywhere.

$config = new \Zend\Config\Config( include APPLICATION_PATH.'/config/autoload/global.php' ); 

echo $config->myconfig;

define APPLICATION_PATH in public/index.php