In Yii2, path aliases are used to represent file paths or URL paths so that we don't hardcode paths or URLs directly into our application. In Yii2, aliases always start with the @
symbol so that Yii knows how to differentiate it from a file path or URL.
Aliases can be defined in several ways. The most basic way to define a new alias is to call \Yii::setAlias()
:
\Yii::setAlias('@path', '/path/to/example'); \Yii::setAlias('@example, 'https://www.example.com');
Aliases can also be defined in the application configuration file by setting the alias option as follows:
return [ // ... 'aliases' => [ '@path => '/path/to/example, '@example' => 'https://www.example.com', ], ];
Also, aliases can be easily retrieved using \Yii::getAlias()
:
\Yii::getAlias('@path') // returns /path/to/example \Yii::getAlias('@example') // returns https://www.example.com
Several places in Yii are alias-aware and will accept aliases as inputs. For example, yii\caching\FileCache
accepts a file alias as an alias for the $cachePath
parameter:
$cache = new FileCache([ 'cachePath' => '@runtime/cache', ]);
Note
For more information on path aliases, check out the Yii documentation at http://www.yiiframework.com/doc-2.0/guide-concept-aliases.html.