Changing Yii2 application’s configuration at runtime

You can’t use Yii::t() method inside Yii2 application’s configuration, right?

I mean… you can use it (application won’t fail), but you will always get string passed as method’s param in return, instead of actual translation, no matter, what language is currently set in your application.

This makes “How to translate application title (or any other configuration parameter)” a quite good question.

Since you can’t (or shouldn’t) use this:

$config = [
    'language' => 'pl',
    'sourceLanguage' => 'en',
    'name' => Yii::t('app', 'Title of My Application'),
]

in config/web.php then we should rather look into a bit different place.

How about web/index.php? How about changing this:

(new yiiwebApplication($config))->run();

into something like this:

$application = new yiiwebApplication($config);

$application->name = Yii::t('app', 'English Title That Will Be Correctly Translated');

$application->run();

Well… that’s actually all.

At reading configuration array phase neither Yii::$app is created nor Yii::t() works as we expect it to work. But, when application object is created and configuration is parsed, you can do virtually anything.

With the very same approach you can set some other configuration options or application parameters that requires Yii environment to be fully initiated — for example: setting paths, that are using aliases. I.e.:

$application = new yiiwebApplication($config);

$application->name = Yii::t('app', 'English Title That Will Be Correctly Translated');
$application->params['uploadPath'] = Yii::getAlias('@webroot').DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'images';

$application->run();

If you’d try to do this directly in /config/params.php, it would fail, because Yii::getAlias('@webroot') (or any other alias) is not set at the reading configuration stage.

Leave a Reply