Home >Backend Development >PHP Tutorial >Examples of how to use Thinkphp5 behavior
ThinkPHP is a free, open source, fast and simple object-oriented lightweight PHP development framework. This article mainly introduces a summary of the behavior usage of Thinkphp5. Friends who need it can refer to it. I hope it can help everyone.
Create a behavior directory under the application or module, and the directory has a built-in behavior file Test.PHP (the home module is used as an example below)
namespace app/home/behavior;//注意应用或模块的不同命名空间 class Test { public function run(&$params) { echo $params; } }
Method 1
1. In the entry file, add: define('APP_HOOK',true);
2. Build the tags.PHP file under the home module to define the behavior
return [ 'app_init'=> [ 'app//home//behavior//Test', //注意行为的命名空间(下同) ], 'zzzzz'=> [//自定义标签位 'app//home//behavior//Test', ], //................. ];
3. Detect the required places in the controller method Listen to the behavior
/think/Hook::listen('app_init',$params);//参数为变量(下同) /think/Hook::listen('zzzzz',$params);//自定义
Method 2
1. Bind the behavior to the label position in the public file of the home module (common.PHP) or the controller method
/think/Hook::add('app_init','app//home//behavior//Test'); /think/Hook::add('zzzz','app//home//behavior//Test');//自定义
2. Control Listen to the behavior where needed in the controller method
/think/Hook::listen('app_init',$params); /think/Hook::listen('zzzzz',$params);//自定义
Method 3
Directly execute the behavior where 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='闭包函数'; /think/Hook::add('zzzz',function($a){ var_dump($a);}); /think/Hook::listen('zzzz',$a);
Method 5
Bind the behavior class 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 behavior to the label in the public file (common.PHP) of the home module or the controller method
/think/Hook::add('app_init','app//home//behavior//Test'); /think/Hook::add('app_end','app//home//behavior//Test');
3. Listen for the behavior where needed in the controller method
/think/Hook::listen('app_init',$params); /think/Hook::listen('app_end',$params);
Related recommendations:
thinkPHP5 uses the laypage paging plug-in to implement list paging function_php example
The most detailed ThinkPHP5 custom paging class Tutorial
Introduction to the method of implementing paging function in thinkphp5
The above is the detailed content of Examples of how to use Thinkphp5 behavior. For more information, please follow other related articles on the PHP Chinese website!