I know this is old but, I found this question while I was searching an answer. I also find a nice guide, link below.
One of the ways to do it to create a component and bootstrap it, like so:
Create a file in, say, common/components/LanguageSelector.php
<?php
namespace common\components;
use yii\base\BootstrapInterface;
class LanguageSelector implements \yii\base\BootstrapInterface
{
public $supportedLanguages = [];
public function bootstrap($app)
{
$preferredLanguage = $app->request->getPreferredLanguage($this->supportedLanguages);
$app->language = $preferredLanguage;
}
}
I'm using advanced app template, you can adjust the file location and namespace as needed.
Then, in your config file, you need to add this component, just like you are adding another component like debug, or log components, like so:
'components' => [
'languageSelector' => [
'class' => 'common\components\LanguageSelector',
'supportedLanguages' => ['en-US', 'tr-TR'],
],
],
Also, you need to add this component to bootstrapped components in your config file:
'bootstrap' => ['languageSelector', ...]
This approach does not rely on cookies however, it relies on the language of the client browser. You also can find an example on below page in how to achieve preference based language selection. But basically what you need to do is, in your languageSelector component, getting the value from the cookie and change the language accordingly. If there is not a cookie present in the user browser, you can fallback to the browser language.
https://github.com/samdark/yii2-cookbook/blob/master/book/i18n-selecting-application-language.md