Example Analysis of Using Hook in thinkPHP

  • 2021-08-21 19:48:16
  • OfStack

In this paper, the use of hooks in thinkPHP is described with examples. Share it for your reference, as follows:

In front of the introduction of thinkPHP hooks in the two configuration call methods, here to step 1 analysis 1 under the use of hooks.

1 Create hook behavior:

The label bits defined by ourselves can be placed directly in Think\ Behaviors or in the application directory, for example, under Home module, create a new folder of Behaviors, and create a new one in the folder

Tag name + Behavior. class. PHP

Note: For the reason why Behavior is required, see the code:


static public function exec($name, $tag,&$params=NULL) {
    if('Behavior' == substr($name,-8) ){
      //  Behavior extension must be used with run Entry method 
      $tag  =  'run';
    }
    $addon  = new $name();
    return $addon->$tag($params);
}

My own custom label name here is My


namespace Behavior;
use Think\Behavior;
class MyBehavior extends Behavior
{
  public function run(&$arg){
    echo 'Thinkphp  In '.$arg['name'].' Function ,'.$arg['value'].' Medium ...';
  }
}

Pay attention to the case of class name

2 Add hooks to the hook set

Method 1 (manual registration): Add 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 case) the contents of tags. php:


return array(
//'action_begin'=>array('Home\\Behaviors\\test','Home\\Behaviors\\test'),
 //1 A tag bit can have multiple behaviors, just use an array. 
 //  If it is 3.2.1 Version   You need to change to 
 // 'action_begin'=>array('Home\\Behaviors\\testBehavior','Home\\Behaviors\\testBehavior'),
 'my'=>array('Behaviors\\MyBehavior')
);

3 Add monitoring: (I just use direct monitoring in the template here)

If the hook method cannot be found here, please add it in ThinkPHP/Common/functions. php (of course, it can also be in other public files):


function hook($hook,$params= array()){
  \Think\Hook::listen($hook,$params);
}

Finally, use it in the template:


{:hook('my', array('name'=>' Hook ','value'=>' Learning '))}

For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: