Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access Application Config from View in Zend Framework 2 (zf2)?

I wanted to access the application config from a view. How can I achieve that in ZF 2?

like image 573
Omar S. Avatar asked May 14 '13 11:05

Omar S.


2 Answers

Actually you shouldn't need to access application config inside a view. In MVC, views just responsible for displaying/rendering data (output) and shouldn't contain any business or application logic.

If you really want to do that you can simply pass to view in your controller something like this:

<?php
namespace YourModule\Controller;

use Zend\View\Model\ViewModel;

// ...

public function anyAction()
{
    $config = $this->getServiceLocator()->get('config');
    $viewModel = new ViewModel();
    $viewModel->setVariables(array('config' => $config ));
    return $viewModel;
}

// ...
?>

So in your view.phtml file;

<div class="foo">
 ...
 <?php echo $this->config; ?>
 ...
</div>
like image 151
edigu Avatar answered Oct 23 '22 21:10

edigu


You should create a view helper.

Config.php

<?php
namespace Application\View\Helper;

class Config extends \Zend\View\Helper\AbstractHelper
{
    public function __construct($config)
    {
        $this->key = $config;
    }

    public function __invoke()
    {
        return $this->config;
    }

}

Module.php or theme.config.php

return array(
    'helpers' => array(
    'factories' => array(
        'config' => function ($sm) {
            return new \Application\View\Helper\Config(
                    $sm->getServiceLocator()->get('Application\Config')->get('config')
            );
        },
    )
),
);

Then you can use config variables in any view.

echo $this->config()->Section->key;
like image 32
Mikhail Prosalov Avatar answered Oct 23 '22 19:10

Mikhail Prosalov