Setting aliases in Yii2 within the app config file

2020-02-09 11:39发布

问题:

I'm trying to set an alias in Yii2 but I'm getting a Invalid Parameter / Invalid path alias for the below code that is placed in the app config file:

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

If I remove the @ it works.

I noticed you can do this:

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

...but I would prefer to set it within the app config file. Is this not possible? If so, how?

回答1:

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

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

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

Before:

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

If run echo in view file:

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

Show like this:

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



回答2:

Yii2 basic application

To set inside config file, write this inside $config array

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

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

But as mentioned here,

The @yii alias is defined when you include the Yii.php file in your entry script. The rest of the aliases are defined in the application constructor when applying the application configuration.

If you need to use predefined alias, write one component and link 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 config file, add 'app\components\Aliases' to bootstrap array

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


回答3:

@webroot alias is not available at this point, it is defined during application bootstrap :

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

No need to define this alias yourself, you should simply use another one :

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


回答4:

To improve on @vitalik_74's answer

you can place it in config/web.php instead(if you are using the basic yii app, I'm not sure about the main config file in the advance version, but the same applies, just put the require on the main config file) so that it gets shorten to:

require(__DIR__ . '/aliases.php');


标签: php yii yii2