Yii2: configuration of the framework, components and modules
Author: Rafal MarguzewiczPublished:
Categories: Yii2
Tags: configuration • framework
Configuration file Yii2 basic template is in the path
config/web.php
. In case of configuration Yii2 advanced template, frontend and backend have their own configuration files: frontend/config/main.php
and backend/config/main.php
Additionally, get the configuration from a common file common/config/main.php
For some reason, I recommend choose Yii2 on basic template. Simply, the configuration is easier.
Each of these files gets additional configurations from other files. Often, this is a file with access data to data base app/config/db.php
, with parameters app/config/params.php
which will be available throughout the app (e.g. admin email address).
Configuration concept in Yii2
The configuration file is an associative array of which :
- Keys are class properties of yii\web\Application
- Syntax is based on Yii2 configuration rules
I will approximate this concept by example component, which increases the possibilities framework Yii2 of send emails.
'components' => [
...
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'localhost',
'username' => 'username',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
],
],
...
],
The name of component is the same as the key name – mailer and we can refer to component via code Yii::$app->mailer
. In case configuring modules or components required is set class [‘class’ => class_of_component], i my example value is yii\swiftmailer\Mailer
. If we do not know the options of class, we can find on Yii2 API page. In the context of configuration, we are interesting sectionproperties, in which we have possible options, with types of parameters.
Example configuration in Yii2
I will present the most commonly used options. For easy i pasted merged configuration file.
<?php return [
'language' => 'pl',
'sourceLanguage'=>'en',
'homeUrl' => '/',
'charset' => 'UTF-8',
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'basePath' => dirname(__DIR__),
'modules' => [
'menu' => [
'class' => '\pceuropa\menu\Menu',
],
'formbuilder' => [
'class' => '\pceuropa\forms\Module',
'config' => ['table' => 'form_']
],
],
'components' => [
'request' => [
'cookieValidationKey' => 'secret_key',
'csrfParam' => '_csrf-backend',
'baseUrl' => '/',
],
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=nazwa_bazy',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
//'cache' => ['class' => 'yii\caching\FileCache',],
'session' => ['class' => 'yii\web\DbSession',
'name' => 'bronze_cookie',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\DbTarget',
'levels' => ['error', 'warning'],
],
[
'class' => 'yii\log\EmailTarget',
'mailer' =>'mailer',
'except' => ['yii\web\HttpException:404',],
'levels' => ['error'],
'message' => [
'from' => ['info@pceuropa.net'],
'to' => ['info@pceuropa.net'],
'subject' => 'Log message from yii2',
],
],
],
],
'user' => [
"class" => "yii\web\User",
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
// 'returnUrl' => 'site/contact',
],
'urlManager' => [
'baseUrl' => '',
'hostInfo' => 'http://example.dev',
'class' => 'codemix\localeurls\UrlManager',
'languages' => ['pl', 'en'],
'languageParam' => 'lang',
'enableDefaultLanguageUrlCode' => false,
'enableLanguagePersistence' => false,
'enableLanguageDetection' => false,
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'/' => 'site/index',
'<action:\w+>' => 'site/<action>',
'<controller:\w+/?>' => '<controller>/index',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
],
],
'authManager' => ['class' => 'yii\rbac\DbManager',],
'i18n' => [
'translations' => [
'app' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@app/messages',
'fileMap' => [ 'app' => 'app.php', ]
]
]
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@app/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'imap.google.com',
'username' => 'info@domain.net',
'password' => 'pass',
'port' => '465',
'encryption' => 'ssl',
],
],
'assetManager' => [
'class' => 'yii\web\AssetManager',
'bundles' => [
'yii\web\JqueryAsset' => [ 'js' => [ '//code.jquery.com/jquery-3.2.1.min.js'] ],
'yii\bootstrap\BootstrapAsset' => [ 'css' => [ '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'] ],
'yii\bootstrap\BootstrapPluginAsset' => [ 'js' => [ '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'] ]
]
],
],
'params' => [
'adminEmail' => 'admin@example.com',
'supportEmail' => 'support@example.com',
'user.passwordResetTokenExpire' => 3600,
],
'aliases' => [
'@www' => 'http://pceuropa.dev',
'@img' => '@www/images/',
'@img_path' => '@app/web/images',
'@views' => '@app/views',
]
];
Description of configuration options
- language – current language page, application message language.
vendor/yiisoft/yii2/messages
and attribute lang in head page. This option affects the i18n component (linia 83) - sourceLanguage – specifies the original language of the page. It is needed in case of application have more than one language. For better compresions different between sourceLAnguage and language see option/component i18n, which is based on these options.
- modules – here add new modules. The key is the modue ID. ne.g. /forms/controller/action. Modules is good way to manage the namespace e.g. add new module admin. This is useful in the case use Yii2 template basic. Here we can pass the module configuration data. Names of properties must to be the same than public properties of class module
- components
- request – basic option is
cookieValidationKey
– cookie security key. In the case of breaking cookies security – change key – outdated old cookies and will force the use of new.
baseUrl
– an option useful when application is in subfolder (e.g. backend – panel admin) - db – data access to data base (SQL, MongoDb, Redis, ElasticSearch and more
- log – event logging. I prefer to create logs in database and send logs by email in case of errors (exclusion events 404). By crawlers, you can receives to many notifications, then easier to overlook the most important. Thanks to this component can fix problems, after that, the user will end up writing an email saying something is not working.
- user – login, register, managing user authorization. Value
identityClass
is the class name, whose methods are responsible for the identity of the users. - urlManager – Url’s management.
enablePrettyUrl
set on true – runs friendly for search engine and humans pretty URL. In rulerule
need to set rules for rewrite address e.g. /index.php?r=kontroler/view&id=3 rewrite to /kontroler/3.baseUrl i hostInfo are uses by class yii\helpers\Url to generate URL’s. If our site is in subfolder than
baseUrl
(also of module request) need to set e.g. ‘/admin.hostInfo
is need to generate absolutes URL. On this example you can see that I use class external software vendors. This extended URL manager about the possibility of prefix languages (pl,en) and additional configurations options. Now automatically framework change address form /controller/3 to /pl/controller/3. IfenableDefaultLanguageUrlCode
is false then /en/controller/3 is /controller/3.showScriptName
on false – framework not show index.php in URL - authManager – manager authorization. Class yii\rbac\DbManager allows RBAC authorization. I recommend RBAC because if we do not need authorisation based on rule and role but only simple authorization logged/quest, we will be able to choose.
- i18n – component responsible for internationalisation. We can add source of translations (files 0 yii\i18n\PhpMessageSource, databases yii\i18n\DbMessageSource)
- mailer – the selection of the management class of mail dispatch fell on
yii\swiftmailer\Mailer
. Atomic solution – set correct SMTP data access and you can sleep peacefully. - assetManager – you can change default CSS i Js. E.g. if you need minification localy version.
'bundles' => [ 'yii\web\JqueryAsset' => [ 'js' => [ 'jquery.min.js'] ], 'yii\bootstrap\BootstrapAsset' => [ 'css' => [ 'css/bootstrap.min.css'] ], 'yii\bootstrap\BootstrapPluginAsset' => [ 'js' => [ 'js/bootstrap.min.js'] ] ]
- request – basic option is
- params – global parameters, access in all application. To get the value of
adminEmail
use code: Yii::$app->params[‘adminEmail’]. If you need set path or URL better to use aliases - aliases – Yii2 have many default aliases path and URL. If you need assign address of location of docyments, you can do it here. And in the app to use A
Url::to('@img/photo.png')
. In case re-factorization, need just change one alias.
Popular search terms:
|