Manage translations from the Dependency Injector

Hello the team,

i saw few topics to manage multi languages translations with phalcon, but i fail to implement the service from the Dependency Injector.

From now, i have this part of code :

1) In the component ControllerBase :

<?php

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller {

protected function getTranslation()
{
  // Ask browser what is the best language
  $language = $this->request->getBestLanguage();

  // Check if we have a translation file for that lang
  if (file_exists(APP_PATH ."/app/messages/" . $language . ".php")) {
      require APP_PATH ."/app/messages/" . $language . ".php";
  } else {
      // Fallback to some default
      require APP_PATH ."/app/messages/en.php";
  }

  // Return a translation object
  return new \Phalcon\Translate\Adapter\NativeArray(
      array(
          "content" => $messages
      )
  );
}

}

2) Then in a child other controller, i can manage the translations passing it to my view through :

$this->view->t = $this->getTranslation();

3) Finally, i can use translations in my view with:

<?php echo $t->_("hi"); ?>

To use it directly from my Dependency Injector, I tried to set it in the configuration of my services with:

$di->setShared('trans', function() {

require APP_PATH ."/app/messages/en.php";

// Return a translation object
return new \Phalcon\Translate\Adapter\NativeArray(
  array(
      "content" => $messages
  )
);

});

Here the content of the file "en.php" :

<?php

$messages = array( "hi" => "Hello" );

Do you have any idea why this solution does not work ?

Thank you for your help, Berni.



11.5k

why don't you use PHP native gettext?

It is another way to manage translations. The way to manage them through the Phalcon services is a good solution. It works perfectly through controllers but not through the dependencies injection. So, if anybody may have any idea, it could be interesting to know the problem and improve the framework if needed :)