We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

DI Services in Volt

I know there are other topics with this question, but that topics didn't resolve my problem.

I'm using Phalcon Incubator to use translations from the database. The translate database adapter is added to the Dependency Injector in the bootstrap. The translator service is available in every controller.

$oDi->setShared('translator', function() use($oDb) {
    $oRequest = new Request();
    $oTranslator = new Phalcon\Translate\Adapter\Database (
        array(
            'db' => $oDb,
            'language' => $oRequest->getBestLanguage()
        )
    );
    return $oTranslator;
});

I thought everything in the Dependency Injector is also availabe in the Volt templates. I can use other services like session and flashSession in Volt without any problem. But the translator service give me this message:

Notice: Undefined variable: translator

I think I have to add the translator service manually with setDI(), because it is not in the default DI. I added this line to the code, but I still get the Undefined message.

$this->view->setDI($oDi);

This is working, but there must be another solution.

$this->view->setVar('translator', $this->di->getShared('translator'));

Can someone help me?

edited Jun '15

You don't have to pass the translator to the view, if it's a registered service you can use it in the views as follows:

Volt:

{{ translator.query("some") }}

PHTML

<?php echo $this->translator->query("some"); ?>


1.2k

I have registered the translator and view in the bootstrap.


$oDi->setShared('translator', function() use($oDb) {
    $oRequest = new Request();
    $oTranslator = new Phalcon\Translate\Adapter\Database (
        array(
            'db' => $oDb,
            'language' => $oRequest->getBestLanguage()
        )
    );
    return $oTranslator;
});

$oDi->set('view', function() {
    $oView = new Phalcon\Mvc\View\Simple;
    $oView->registerEngines(array(
        '.volt' => 'Phalcon\Mvc\View\Engine\Volt'
    ));
    return $oView;
});

When I use this in Volt, it gives me the message: Notice: Undefined variable: translator

{{ translator.query('some') }}

I can use the translator in the controllers as follows, so the service is registered.

$this->translator->_('some')