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

Omar S. picture Omar S. · May 14, 2013 · Viewed 12.9k times · Source

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

Answer

edigu picture edigu · May 14, 2013

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>