Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting aliases in Yii2 within the app config file

Tags:

php

yii

yii2

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?

like image 926
Brett Avatar asked Mar 01 '15 18:03

Brett


3 Answers

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',        
],
like image 177
abdulwadood Avatar answered Nov 17 '22 09:11

abdulwadood


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/

like image 35
vitalik_74 Avatar answered Nov 17 '22 11:11

vitalik_74


@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/',
],
like image 2
soju Avatar answered Nov 17 '22 11:11

soju