Home> PHP Framework> YII> body text

How to use aliases in yii2 framework

王林
Release: 2021-03-08 16:53:21
forward
3041 people have browsed it

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');
Copy after login

You can get it now:

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

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

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

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:


        
Copy after login

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__).'../../config')).'/constant.php';
Copy after login

Or use an alias to introduce:

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

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)

'aliases'=>[ '@ww'=>dirname(__FILE__).'/constant.php', ],
Copy after login

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!

Related labels:
source:www.yii-china.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!