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

3

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)?

Efficient answered 18/4, 2013 at 12:40 Comment(6)
I'd suggest a view helper that's injected with the config, substitute the model class with config in the answer I just gave here -> #16083029, and use your helper as a proxyJohnathon
Definitely the approach provided by @Johnathon however there'd be strong questions about why you would really need them. A view should render, nothing else, it shouldn't even bother about any single config. That's the controllers job. What exactly are you trying to do?Lantz
You could certainly use both those methods, but I would tend to keep it out of the view as Sam suggests :)Succinic
@Lantz I want to permit displaying the web analytics JS within the dev/staging environment.Efficient
Definitely a solution for a viewHelper displayAnalytics() - the viewHelper would access the config via ServiceManager and then either output an empty string or the functional analytics code. See answer provided by crisp ;)Lantz
Thank you guys! +1 for Cris for a solution hint and +2 for Sam for a reasonable notice about handling of views and another solution hint. :) I've implemented now the first solution and will also try it with the second one. I see, that the displayAnalytics() view helper way is cleaner and better for my concret case. But the original question was "How to access configs from autoloaded config files in a layout / view script [...] ?". So, I'll post both solutions.Efficient
E
3

(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');;
}
?>
Efficient answered 18/4, 2013 at 14:39 Comment(0)
E
0

So this solution becomes more flexible:

/config/application.config.php

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

/config/autoload/whatever.local.php and /config/autoload/whatever.global.php

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

ContentForEnvironment view helper

<?php
namespace MyNamespace\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\View\HelperPluginManager as ServiceManager;

class ContentForEnvironment extends AbstractHelper {

    protected $serviceManager;

    public function __construct(ServiceManager $serviceManager) {
        $this->serviceManager = $serviceManager;
    }

    /**
     * Returns rendered partial $partial,
     * IF the current environment IS IN $whiteList AND NOT IN $blackList,
     * ELSE NULL.
     * Usage examples:
     * Partial for every environment (equivalent to echo $this->view->render($partial)):
     *  echo $this->contentForEnvironment('path/to/partial.phtml');
     * Partial for 'live' environment only:
     *  echo $this->contentForEnvironment('path/to/partial.phtml', ['live']);
     * Partial for every environment except 'development':
     *  echo $this->contentForEnvironment('path/to/partial.phtml', [], ['development', 'staging']);
     * @param string $partial
     * @param array $whiteList
     * @param array $blackList optional
     * @return string rendered partial $partial or NULL.
     */
    public function __invoke($partial, array $whiteList, array $blackList = []) {
        $currentEnvironment = $this->serviceManager->getServiceLocator()->get('Config')['environment'];
        $content = null;
        if (!empty($whiteList)) {
            $content = in_array($currentEnvironment, $whiteList) && !in_array($currentEnvironment, $blackList)
                ? $this->view->render($partial)
                : null
            ;
        } else {
            $content = !in_array($currentEnvironment, $blackList)
                ? $this->view->render($partial)
                : null
            ;
        }
        return $content;
    }

}

Application Module class

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

Layout view script

<?php echo $this->contentForEnvironment('path/to/partial.phtml', [], ['development', 'staging']); ?>
Efficient answered 18/4, 2013 at 12:41 Comment(0)
E
0

My implementation/interpretation of Sam's solution hint for the concret goal (to permit displaying the web analytics JS within the dev/staging environment):

DisplayAnalytics view helper

<?php
namespace MyNamespace\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\View\HelperPluginManager as ServiceManager;

class DisplayAnalytics extends AbstractHelper {

    protected $serviceManager;

    public function __construct(ServiceManager $serviceManager) {
        $this->serviceManager = $serviceManager;
    }

    public function __invoke() {
        if ($this->serviceManager->getServiceLocator()->get('Config')['environment'] == 'development') {
            $return = $this->view->render('partials/partial-bar.phtml');
        }
        return $return;
    }

}

Application Module class

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

Layout view script

<?php echo $this->displayAnalytics(); ?>
Efficient answered 18/4, 2013 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.