First of all, A hook is a trigger mechanism, like a trap. When the program runs to a certain place, the trap will be triggered and then executed. After the execution of this Hook is completed, the system continues based on the different results of the execution.
So, what is the principle of thinkphp hook (Hook) mechanism?
1. The framework calls the import method in the Hook class in the \Think\Think->start()
method to batch load the mode. Behavior: The default is the configuration file in \Model\common.php
, which defines the behavior extension
##2. Monitor the behavior of the tag mark through the Hook:listen() method. Define an array tags in the Hook class: tag is the key; the Behavior behavior is the value. Execute the behavior plug-in of the tag through Hook:exec()
/** * 监听标签的插件 * @param string $tag 标签名称 * @param mixed $params 传入参数 * @return void */ static public function listen($tag, &$params=NULL) { if(isset(self::$tags[$tag])) { if(APP_DEBUG) { G($tag.'Start'); trace('[ '.$tag.' ] --START--','','INFO'); } foreach (self::$tags[$tag] as $name) { APP_DEBUG && G($name.'_start'); $result = self::exec($name, $tag,$params); if(APP_DEBUG){ G($name.'_end'); trace('Run '.$name.' [ RunTime:'.G($name.'_start',$name.'_end',6).'s ]','','INFO'); } if(false === $result) { // 如果返回false 则中断插件执行 return ; } } if(APP_DEBUG) { // 记录行为的执行日志 trace('[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]','','INFO'); } } return; } /** * 执行某个插件 * @param string $name 插件名称 * @param string $tag 方法名(标签名) * @param Mixed $params 传入的参数 * @return void */ static public function exec($name, $tag,&$params=NULL) { if('Behavior' == substr($name,-8) ){ // 行为扩展必须用run入口方法 $tag = 'run'; } $addon = new $name(); return $addon->$tag($params); }
The above is the detailed content of thinkphp hook means. For more information, please follow other related articles on the PHP Chinese website!