Setting aliases in Yii2 in the application configuration file

I try to install alias in Yii2 , but I get an Invalid Parameter / Invalid path alias for the code below, which fits in the application configuration file:

 'aliases' => [ // Set the editor language dir '@editor_lang_dir' => '@webroot/scripts/sceditor/languages/', ], 

If I remove @ , it will work.

I noticed that you can do this:

 Yii::setAlias('@foobar', '@foo/bar'); 

... but I would prefer to install it in the application configuration file. Is it impossible? If so, how?

+5
source share
4 answers

In the config folder, create the aliases.php file. And put this:

 Yii::setAlias('webroot', dirname(dirname(__DIR__)) . '/web'); Yii::setAlias('editor_lang_dir', '@webroot/scripts/sceditor/languages/'); 

In the web folder in the index.php file the following is require(__DIR__ . '/../config/aliases.php'); : require(__DIR__ . '/../config/aliases.php');

Before:

(new yii\web\Application($config))->run();

If you run the echo file in a file of the form:

echo Yii::getAlias('@editor_lang_dir');

Show the following:

C:\OpenServer\domains\yii2_basic/web/scripts/sceditor/languages/

+6
source

Yii2 main application

To install inside the configuration file, write this inside the $ config array

 'aliases' => [ '@name1' => 'path/to/path1', '@name2' => 'path/to/path2', ], 

Link: http://www.yiiframework.com/doc-2.0/guide-structure-applications.html

But as mentioned here ,

The @yii attribute is determined when the Yii.php file is included in your script entry. The remaining aliases are defined in the application constructor when the application configuration is applied.

If you need to use a predefined alias, write one component and bind it in config bootstrap array

 namespace app\components; use Yii; use yii\base\Component; class Aliases extends Component { public function init() { Yii::setAlias('@editor_lang_dir', Yii::getAlias('@webroot').'/scripts/sceditor/languages/'); } } 

and inside the configuration file, add 'app \ components \ Aliases' to the bootstrap array

  'bootstrap' => [ 'log', 'app\components\Aliases', ], 
+11
source

@webroot alias is not available at the moment, it is determined at application startup time:

https://github.com/yiisoft/yii2/blob/2.0.3/framework/web/Application.php#L60

You do not need to define this alias yourself, you just have to use another:

 'aliases' => [ // Set the editor language dir '@editor_lang_dir' => '@app/web/scripts/sceditor/languages/', ], 
+1
source

To improve the answer @ vitalik_74

you can put it in config / web.php instead (if you are using the main yii application, I'm not sure about the main configuration file in the preliminary version, but the same applies, just request the main configuration file) so that it is reduced to :

 require(__DIR__ . '/aliases.php'); 
+1
source

Source: https://habr.com/ru/post/1214432/


All Articles