Setting aliases in Yii2 within the app config file

后端 未结 4 766
孤独总比滥情好
孤独总比滥情好 2020-12-16 05:13

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

相关标签:
4条回答
  • 2020-12-16 05:26

    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',        
    ],
    
    0 讨论(0)
  • 2020-12-16 05:28

    @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/',
    ],
    
    0 讨论(0)
  • 2020-12-16 05:33

    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');
    
    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题