Home  >  Article  >  PHP Framework  >  thinkphp hook implementation method

thinkphp hook implementation method

尚
forward
2020-04-20 09:09:393070browse

A hook is a trigger mechanism, like a trap. When the program runs to a certain place, the trap will be triggered, and then the Hook will be executed. After the execution is completed, the system will continue based on the different results of the execution.

thinkphp hook implementation method

The framework calls the import method in the Hook class in the \Think\Think->start() method. Batch loading mode behavior: The default is \Model\common.php Configuration file, which defines behavior extensions.

thinkphp hook implementation method

2. Monitor the behavior of tag tags through the Hook:listen() method. An array tags:tag is defined in the Hook class as key; Behavior is value. Execute the marked behavior plug-in 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);
    }

Recommended tutorial: thinkphp tutorial

The above is the detailed content of thinkphp hook implementation method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete