Example site built with Yii2: NFT Viewer

8. Aliases

Yii offers a shorthand of sorts to refer to file paths and URLs so that you do not have to hard-code these into your application. They are basically defined constants and always are prefixed with an @ symbol.

8.1 Commonly Used Predefined Aliases

There are a number of predefined aliases available to you by default. Some of the more commonly used aliases are as follows:

  • @yii: The path to the core Yii application files.
  • @app: A reference to the root path of the application.
  • @web: The base URL pointing to your application.
  • @webroot: The document root directory as specified in your Apache config.

Yii2 Advanced Template defines these additional aliases:

  • @common: Path to the 'common' root directory.
  • @frontend: Path to the 'frontend' root directory.
  • @backend: Path to the 'backend' root directory.
  • @console: Path to the 'console' root directory.

8.2 Defining Aliases

You can define your own aliases by using the setAlias function.

To set an alias of a file path, you would use the following format:

Yii::setAlias('@foo', '/path/to/foo');

You can also set an alias to a URL as such:

Yii::setAlias('@bar', 'http://www.example.com');

You can even use an alias to define another alias:

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

You also have the option to set any aliases in the config file. You could add the following to the $config array:

'aliases' => [
	'@foo' => '/path/to/foo',
	'@bar' => 'http://www.example.com',
],

8.3 Resolving Aliases

You get the alias value by using Yii::getAlias(). If @foo and @bar where set as above, you would access them as such:

$foo = Yii::getAlias('@foo');
$bar = Yii::getAlias('@foo');

If you echoed these out, you would get the following:

echo $foo;

Displays /path/to/foo

echo $bar;

Displays http://www.example.com

You can also append additional path directors.

echo Yii::getAlias('@foo/bar/file.php');

Displays /path/to/foo/bar/file.php

8.4 Using Aliases

Aliases are recognized in many places in Yii without needing to call Yii::getAlias() to convert them into paths or URLs. Sometimes the @alias is used as part of the path.

For example, setting the path to the file cache, you would do as such:

$cache = new FileCache([
    'cachePath' => '@runtime/cache',
]);