Yii Tutorial on Yii Aliases

aliases help you not to hard-code absolute paths or urls in your project. an alias starts with the @ character.

to define an alias you should call the yii::setalias() method −

// an alias of a file path
yii::setalias('@alias', '/path/to/alias');
// an alias of a url
yii::setalias('@urlalias', 'http://www.google.com');

you can also derive a new alias from an existing one −

yii::setalias('@pathtosomewhere', '@alias/path/to/somewhere');

you can call the yii::setalias() method in the entry script or in a writable property called aliases in the application configuration −

$config = [
   'id' => 'basic',
   'basepath' => dirname(__dir__),
   'bootstrap' => ['log'],
   'components' => [
      'aliases' => [
         '@alias' => '/path/to/somewhere',
         '@urlalias' => 'http://www.google.com',
      ],
      //other components...
   ]
]

to resolve alias, you should call the yii::getalias() method.

yii predefines the following aliases −

  • @app − the base path of the application.

  • @yii − the folder where the baseyii.php file is located.

  • @webroot − the web root directory of the application.

  • @web − the base url of the application.

  • @runtime − the runtime path of the application. defaults to @app/runtime.

  • @vendor − the composer vendor directory. defaults to @app/vendor.

  • @npm − the root directory for npm packages. defaults to @vendor/npm.

  • @bower − the root directory for bower packages. defaults to @vendor/bower.

now, add a new function called actionaliases() to the sitecontroller −

public function actionaliases() {
   yii::setalias("@components", "@app/components");
   yii::setalias("@imagesurl", "@web/images");
   var_dump(yii::getalias("@components"));
   var_dump(yii::getalias("@imagesurl"));
}

in the above code, we created two aliases: @components for application components and @imagesurl for url where we stored all application images.

type http://localhost:8080/index.php?r=site/aliases, you will see the following output −

set aliases