Home  >  Article  >  PHP Framework  >  How to use thinkphp5 hooks

How to use thinkphp5 hooks

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-08-23 09:45:093014browse

How to use thinkphp5 hooks

1、创建钩子行为

我们自己定义的标签位可以直接放在Think\Behaviors中,也可以放在应用目录中,比如说Home模块下,新建一个Behaviors的文件夹,在文件夹内新建:

标签名+Behavior.class.PHP

注:需要带Behavior的原因,见代码:  

static public function exec($name, $tag,&$params=NULL) {
    if('Behavior' == substr($name,-8) ){
      // 行为扩展必须用run入口方法
      $tag  =  'run';
    }
    $addon  = new $name();
    return $addon->$tag($params);
}

相关推荐:《ThinkPHP教程

在这里我自己自定义的标签名是My  

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

注意类名大小写

2、将钩子添加进钩子集中

方法一(手动注册):直接在控制器中添加:

Hook::add('addd','Behavior\\adBehavior');

方法二(自动注册):

在Conf文件夹里面(完整路径D:\think\application\Home\Conf\tags.php,当然这是我的情况)tags.php的内容: 

return array(
//'action_begin'=>array('Home\\Behaviors\\test','Home\\Behaviors\\test'),
 //一个标签位可以有多个行为,使用数组即可。
 // 如果是3.2.1版本 则需要改成
 // 'action_begin'=>array('Home\\Behaviors\\testBehavior','Home\\Behaviors\\testBehavior'),
 'my'=>array('Behaviors\\MyBehavior')
);

3、添加监听(我这里才用模板中直接监听使用)

此处如果报找不到hook方法,请在ThinkPHP/Common/functions.php中添加(当然也可以在其他公共文件): 

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

最后在模板中使用:  

{:hook('my', array('name'=>'钩子','value'=>'学习'))}

The above is the detailed content of How to use thinkphp5 hooks. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn