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

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
        ]));
        $this->add($username);
    }
}

//...

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.



145.0k
Accepted
answer
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.



11.1k
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!