PHP code example of yidas / yii2-language

1. Go to this page and download the library: Download yidas/yii2-language library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yidas / yii2-language example snippets


return [
    'bootstrap' => ['log', 'lang'],
    'language' => 'en-US',
    'components' => [
        'lang' => [
            'class' => 'yidas\components\Language',
            'languages' => [
                0 => 'en-US',
                1 => 'zh-TW',
                2 => 'zh-CN',
            ],
            'maps' => [
                'html' => [
                    0 => 'en',
                    1 => 'zh-Hant',
                    2 => 'zh-Hans',
                ],
            ],
            // 'storage' => 'session',
            // 'storageKey' => 'language',
        ],
        ...

// `lang` component for example
return [
    'bootstrap' => ['lang'], 
    ...

public string get($map=null)

echo \Yii::$app->lang->get();  // en-US

echo \Yii::$app->lang->get('html');  // en

public boolean set($language)

\Yii::$app->lang->set('zh-TW');

public string getByMap($mapKey)

echo \Yii::$app->lang->getByMap('html');  // en

public boolean setByMap($mapKey, $mapValue)

$this->setByMap('html', 'zh-Hant');

public boolean isFirstCome()

if (Yii::$app->lang->isFirstCome()) {
    // Detetmine user ip to set current language
} 
else if (Yii::$app->lang->hasStorageRecord()) {
    // Means !(Yii::$app->lang->isFirstCome())
}



namespace app\controllers;

use Yii;
use yii\web\Controller;

/**
 * The Controller for Language converting
 */
class LanguageController extends Controller
{
    public function actionIndex($language='')
    {
        $result = Yii::$app->lang->set($language);
        
        return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
    }
}

return [
    'on beforeAction' => function ($event) {
        // Always fetch language from get-parameter
        $lang = \Yii::$app->request->get('lang');
        // Set to given language with get-parameter
        if ($lang) {
            $result = \Yii::$app->lang->set($lang);
        }
    },
    ...
]