Method Analysis for adding global functions in Yii2, and adding global functions in yii2

Source: Internet
Author: User

Method Analysis for adding global functions in Yii2, and adding global functions in yii2

This example describes how to add a global function in yii2. We will share this with you for your reference. The details are as follows:

Method 1

This method is to write a function directly in the web/index. php file. The sample code is as follows:

// Something code ...... // Global function pr ($ var) {$ template = php_sapi_name ()! = 'Cli '? '<Pre> % s </pre>': "\ n % s \ n"; printf ($ template, print_r ($ var, true); exit ;} (new yii \ web \ Application ($ config)-> run ();

Although this method can be implemented, it is not recommended because the Framework Code is changed and it is difficult to manage if there are more global functions.

Method 2 (recommended)

This method is mainly implemented using composer. Add the following code in the composer. json file:

"Autoload": {"files": ["common/components/GlobalFunctions. php"]},

After adding the file, run the command in the project root directory on the terminal.Composer updateCommand

Then, all our global functions can be written in the GlobalFunctions. php file. If this method is implemented, the IED will be prompted by code.

GetYii is useful in the second method. You can view the source code.

I prefer to add helpers under the directory structure corresponding to the existing namespace.

Sometimes calling helpers seems too long.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.