0

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.

evotopid
  • 5,288
  • 2
  • 26
  • 41
Sina Miandashti
  • 2,087
  • 1
  • 26
  • 40
  • By the way, there shouldn't really be any reason to use \Zend\Registry - objects you put in the registry are essentially global variables, which isn't good form. Instead of using the registry, why not use DI to configure your Translator and inject it where ever it is needed. – superdweebie May 19 '12 at 05:40

2 Answers2

2

add a private class variable private $viewModel. Then create the ViewModel in your construtor, add any variables:

$this->viewModel = new ViewModel();
$this->viewModel->tr = $translator;

Then return $this->viewModel from your action function.

superdweebie
  • 1,576
  • 14
  • 23
1

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')
            )
        ),
Sina Miandashti
  • 2,087
  • 1
  • 26
  • 40