Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Forms and Controllers custom function for translate adapter

At first, I was maked this using $di in the services.php and the next I was used it like this:

$this->translate->_('username'); //return 'Username'

But, I think, this variant is not very comfortable and readable. I have created the translate function in the services.php for use translation in Controllers and Forms:

function translate($resolvedArgs) {
    require "../app/languages/en.php";
    $translate = new NativeArray(['content' => $l]);
    return $translate->_($resolvedArgs);

Then I can use it like this:

// ...

class Account__CreateForm extends Form
    public function initialize()
        // Username
        $username = new Text('username', [
            'placeholder' => translate('username')
        $username->addValidator(new StringLength([
            'messageMinimum' => translate('validation-username'),
            'min'            => 3


But is this method good? Somehow, it seems to me that this is not the best solution. Is it so? How can I do this right? I hope for your help.

edited May '16

I would just use

$this->translate->_('username'); //return 'Username'

If you want to still shorten it you could create AbstractForm which would have method _ which will call _ from translate.

Or you could possibly use trait. I forgot about this one.

edited May '16

Wojciech, thank you:) In the end I've created the ControllerBase.php with the _ function:

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
    public function _($arg)
        return $this->translation->_($arg);

// ...

and use it in the Controller like this:

echo $this->_('username');

I think, that's variant is quite understendable to me and comfortable!