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 update
Command
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.