leinonen / yii2-hostname-language
Simple component which helps to configure the app locale based on the hostname
Installs: 255
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 0
Type:yii2-extension
Requires
- php: >=5.5.0
- yiisoft/yii2: ^2.0
Requires (Dev)
- phpunit/phpunit: 4.8.*
This package is not auto-updated.
Last update: 2020-01-20 05:07:17 UTC
README
This simple component sets the Yii's app locale based on the requests hostname. So for example, if you have my-awesome-app.com which is English version of your site and my-awesome-app.fi which is Finnish and they both point to the same Yii2 app, this component sets the app language automatically on every request.
Installation
Require this package, with Composer, in the root directory of your project.
composer require leinonen/yii2-hostname-language
Configuration
The component is configured in the main config. The pattern for configuring the hosts is 'hostname' => 'language'
. The scheme of the request (http/https) must be left out.
use leinonen\HostnameLanguage\LanguageSelector; 'bootstrap' => ['hostLanguage'], 'components' => [ 'hostLanguage' => [ 'class' => LanguageSelector::class, 'hosts' => [ 'example.com' => 'fi-FI', 'foobar.se' => 'se-SE', ] ] ],
URL Manager
You can also configure a custom URL manager which allows creating urls to another language version of your site. This extends the \yii\web\UrlManager
so all the normal features are also available.
use leinonen\HostnameLanguage\UrlManager; 'components' => [ 'urlManager' => [ 'class' => UrlManager::class, 'enablePrettyUrl' => true, 'showScriptName' => false, ] ]
It then works by feeding a language
parameter to the URL helper function:
Url::to(['site/my-route', 'language' => 'en-US'], true);
Remember to set scheme param to true, cause you need to create absolute urls. If you are already using an url parameter called language it can easily be changed with the config:
'urlManager' => [ ... 'languageParam' => 'lang' ]
And then:
Url::to(['site/my-route', 'lang' => 'en-US'], true);