Search code examples
zend-viewzend-framework2zend-framework-mvc

set some view variable in controller constructer


I have the following code in my zf2 controller:

<?php
namespace Accounting\Controller;

use Zend\Mvc\Controller\ActionController,
Zend\View\Model\ViewModel,
Accounting\Model,
Zend\Paginator,
Accounting\Scripts\CMSTranslator;

class AdminController extends ActionController {

protected $translator;

public function setTranslator(CMSTranslator $translator) {
    $this->translator = $translator;
    return $this;
}

public function __construct(\Doctrine\ORM\EntityManager $em,CMSTranslator $translator) {
    $this->em = $em;

    //$this->translator = new \Zend\Translator\Translator('ArrayAdapter', __DIR__ . '/../../../lang/lang-fa.php', 'fa');
    $this->translator = $translator;

    \Zend\Registry::set('tr', $this->translator);
    // now you can use the EntityManager!
}

As you can see I'm using the zend\translator module.
I want to add it to the view in my controller constructor. I already tried:

return ViewModel(array('tr'=>$translator));

But that doesn't work.

Please help.


Solution

  • Final solution module.config.php

    'Accounting\Controller\AccountingController' => array(
                'parameters' => array(
                    'em' => 'doctrine_em',
                    'translator' => 'Accounting\Scripts\CMSTranslator',
                ),
            ),
            'Zend\View\Helper\Translator' => array(
                'parameters' => array(
                    'translator' => 'Accounting\Scripts\CMSTranslator'
                )
            ),
            'Accounting\Scripts\CMSTranslator' => array(
                'parameters' => array(
                    'options' => array('adapter' => 'ArrayAdapter', 'content' => __DIR__ . '/../lang/lang-fa.php', 'local' => 'fa')
                )
            ),
            'translateAdapter' => array(
                'parameters' => array(
                    'options' => array('adapter' => 'ArrayAdapter', 'content' => __DIR__ . '/../lang/lang-fa.php', 'local' => 'fa')
                )
            ),