ThinkPHP hook usage Example Analysis, thinkphp instance analysis
This example describes how to use hooks in thinkPHP. We will share this with you for your reference. The details are as follows:
We have introduced the two configuration call methods for hooks in thinkPHP. Here we will further analyze how to use the hooks.
1. Create a HOOK:
We can directly store the defined tag bits in Think \ Behaviors or in the application directory. For example, in the Home module, create a folder named Behaviors and create a folder.
Tag name + Behavior. class. PHP
NOTE: For the reason why Behavior needs to be included, see the code:
Static public function exec ($ name, $ tag, & $ params = NULL) {if ('behavior '= substr ($ name,-8 )) {// behavior extension must use the run entry method $ tag = 'run';} $ addon = new $ name (); return $ addon-> $ tag ($ params );}
Here, My custom tag name is
Namespace Behavior; use Think \ Behavior; class MyBehavior extends Behavior {public function run (& $ arg) {echo 'thinkphp '. $ arg ['name']. 'function ,'. $ arg ['value'].... ';}}
Note that the class name is case sensitive.
2. Add the hook to the hook set.
Method 1 (manual registration): Add the following directly to the Controller:
Hook::add('addd','Behavior\\adBehavior');
Method 2 (Automatic Registration ):
In the Conf folder (full path D: \ think \ application \ Home \ Conf \ tags. php, of course this is my situation) content of tags. php:
Return array (// 'Action _ in in' => array ('home \ Behaviors \ test', 'home \ Behaviors \ test '), // a tag can have multiple actions. Use an array. // If the version is 3.2.1, change it to // 'Action _ begin' => array ('home \ Behaviors \ testBehavior ', 'Home \ Behaviors \ testBehavior '), 'My' => array ('behaviors \ MyBehavior '));
3. Add a listener: (I only use the template to directly listen to the listener)
If the hook method cannot be found, add it to ThinkPHP/Common/functions. php (of course, you can also add it to other public files ):
function hook($hook,$params= array()){ \Think\Hook::listen($hook,$params);}
Finally, use the following in the template:
{: Hook ('My, array ('name' => 'hook ', 'value' => 'learn '))}