Home >PHP Framework >YII >How to use aliases in yii2 framework

How to use aliases in yii2 framework

王林
王林forward
2021-03-08 16:53:213149browse

How to use aliases in yii2 framework

What is an alias?

In the actual development process, we will use some absolute paths. But since absolute paths are very long, in order to use paths conveniently, we can give each path a name in Yii, and this name is an alias.

Look at the example directly:

First usage:

First set an alias:

Yii::setAlias('@ww','123');

You can get it now:

echo Yii::getAlias('@ww');//结果是 123

If you do not write the '@' symbol when obtaining:

echo Yii::getAlias('ww');//结果就是ww   字符串直接输出

Second usage:

As mentioned earlier, aliases are for the convenience of using the path , then take a look at specific examples:

For example, if your project often uses some frequently used constants, you can create a new constant.php under config,

constant .php code:

<?php
define(&#39;NAME_STR&#39;,&#39;TOM&#39;);//定义一个常量,值为TOM

When you want to use this constant in the controller, you must introduce this file

(Learning video sharing: php video tutorial)

You can write like this:

include_once(realpath(dirname(__FILE__).&#39;../../config&#39;)).&#39;/constant.php&#39;;

Or use an alias to introduce:

include_once(Yii::getAlias("@app/config/constant.php"));

The third usage:

This usage is In the second optimization, we can write a sentence in the configuration file (web.php) (note: aliases and components are at the same level, do not write the following code into components)

&#39;aliases&#39;=>[
    &#39;@ww&#39;=>dirname(__FILE__).&#39;/constant.php&#39;,
],

Also in Just write include_once(Yii::getAlias('@ww')); in the controller.

Recommended tutorial: yii framework

The above is the detailed content of How to use aliases in yii2 framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.yii-china.com. If there is any infringement, please contact admin@php.cn delete