Summary of Thinkphp5 behavior usage and thinkphp5
Create the behavior directory under the application or module, and create the directory's built-in behavior file Test. PHP (the home module is used as an example below)
Namespace app/home/behavior; // note the different namespaces of the application or module. Test {public function run (& $ params) {echo $ params ;}}
Method 1
1. Add define ('app _ hook', true) to the entry file );
2. Create a tags. php file under the home module to define the behavior
Return ['app _ init '=> ['app // home // behavior // test', // note the namespace of behavior (the same below)], 'zzzzz' => [// custom tag bit 'app // home // behavior // test',], // ......];
3. Local listening behavior required in the Controller Method
/Think/Hook: listen ('app _ init ', $ params); // The parameter is variable (the same below)/think/Hook: listen ('zzzzzzz ', $ params); // custom
Method 2
1. Bind the common. PHP file in the home module or the Controller Method to the tag bit.
/Think/Hook: add ('app _ init', 'app // home // behavior // test');/think/Hook: add ('zzz ', 'app // home // behavior // test'); // custom
2. The desired local listening behavior in the Controller Method
/Think/Hook: listen ('app _ init', $ params);/think/Hook: listen ('zzzzz', $ params); // custom
Method 3
Directly execute the action as needed in the Controller Method
/think/Hook::exec('app//home//behavior//Test','run',$params);
Method 4
Use the closure function directly in the Controller Method
$ A = 'Closure function';/think/Hook: add ('zzzz ', function ($ a) {var_dump ($ a) ;});/think/Hook:: listen ('zzzz ', $ );
Method 5
Behavior class bound to multiple tags
1. Test. PHP is defined as follows:
namespace app/home/behavior;class Test { public function app_init(&$params){ echo 'app_init'; } public function app_end(&$params){ echo 'app_end'; } }
2. Bind the public file (common. PHP) of the home module or Controller Method to the tag bit.
/think/Hook::add('app_init','app//home//behavior//Test');/think/Hook::add('app_end','app//home//behavior//Test');
3. Local listening behavior required in the Controller Method
/think/Hook::listen('app_init',$params); /think/Hook::listen('app_end',$params);
Summary
The above is a summary of Thinkphp5 behavior usage methods introduced by the small editor. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!