Home > PHP Framework > YII > body text

How to use aliases in yii2 framework

王林
Release: 2021-03-08 16:53:21
forward
3097 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:

<?php
define(&#39;NAME_STR&#39;,&#39;TOM&#39;);//定义一个常量,值为TOM
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__).&#39;../../config&#39;)).&#39;/constant.php&#39;;
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)

&#39;aliases&#39;=>[
    &#39;@ww&#39;=>dirname(__FILE__).&#39;/constant.php&#39;,
],
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
Popular Tutorials
More>
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!