Search code examples
configurationzend-framework2production-environmentapplication-settings

How to access configs from autoloaded config files in a layout / view script in Zend Framework 2?


I would like / have to manage some settings in ZF1 style and provide the view with the infomation about the current environment.

/config/application.config.php

return array(
    ...
    'module_listener_options' => array(
        ...
        'config_glob_paths' => array('config/autoload/{,*.}{global,local}.php')
    )
);

/config/autoload/env.local.php

return array(
    // allowed values: development, staging, live
    'environment' => 'development'
);

In a common view script I can do it over the controller, since the controllers have access to the Service Manager and so to all configs I need:

class MyController extends AbstractActionController {

    public function myAction() {
        return new ViewModel(array(
            'currentEnvironment' => $this->getServiceLocator()->get('Config')['environment'],
        ));
    }

}

Is it also possible to get the configs in a common view directly?

How can I access the configs in a layout view script (/module/Application/view/layout/layout.phtml)?


Solution

  • (My implementation/interpretation of) Crisp's suggestion:

    Config view helper

    <?php
    namespace MyNamespace\View\Helper;
    
    use Zend\View\Helper\AbstractHelper;
    use Zend\View\HelperPluginManager as ServiceManager;
    
    class Config extends AbstractHelper {
    
        protected $serviceManager;
    
        public function __construct(ServiceManager $serviceManager) {
            $this->serviceManager = $serviceManager;
        }
    
        public function __invoke() {
            $config = $this->serviceManager->getServiceLocator()->get('Config');
            return $config;
        }
    
    }
    

    Application Module class

    public function getViewHelperConfig() {
        return array(
            'factories' => array(
                'config' => function($serviceManager) {
                    $helper = new \MyNamespace\View\Helper\Config($serviceManager);
                    return $helper;
                },
            )
        );
    }
    

    Layout view script

    // do whatever you want with $this->config()['environment'], e.g.
    <?php
    if ($this->config()['environment'] == 'live') {
        echo $this->partial('partials/partial-foo.phtml');;
    }
    ?>