您的位置 首页 php

php中钩子(hook)的原理与简单应用

对”钩子”这个概念其实不熟悉,最近看到一个php框架中用到这种机制来扩展项目,所以大概来了解下。

php中钩子(hook)的原理与简单应用

所谓 hook 机制,是从Windows编程中流行开的一种技术。其主要思想是提前在可能增加功能的地方埋好(预设)一个钩子,这个钩子并没有实际的意义,当我们需要重新修改或者增加这个地方的逻辑的时候,把扩展的类或者方法挂载到这个点即可。

hook插件机制的基本思想:

在项目代码中,你认为要扩展(暂时不扩展)的地方放置一个钩子函数,等需要扩展的时候,把需要实现的类和函数挂载到这个钩子上,就可以实现扩展了。

思想就是这样听起来比较笼统,看一个网上的实现的例子。

整个插件机制包含三个部分:

1.hook插件经理类:这个是核心文件,是一个应用程序全局Global对象。它主要有三个职责

1>监听已经注册了的所有插件,并实例化这些插件对象。

2>注册所有插件。

3>当钩子条件满足时,触发对应的对象方法。

2.插件的功能实现:这大多由第三方开发人员完成,但需要遵循我们(经理类定义)的规则,这个规则是插件机制所规定的,因插件机制的不同而不同。

3.插件的触发:也就是钩子的触发条件。这是一小段代码,放置在你需要调用插件的地方,用于触发这个钩子。

实现的方案

首先是插件经理类 plugin Manager,这个类要放在全局引用里面,在所有需要用到插件的地方,优先加载。

<?php
/**
*
* 插件机制的实现核心类
 
*/class PluginManager
{
 /**
 * 监听已注册的插件
 *
 * @access private
 * @var array
 */ private $_listeners = array();
 /**
 * 构造函数
 *
 * @access public
 * @return void
 */ public function __construct()
 {
 #这里$plugin数组包含我们获取已经由用户激活的插件信息
 #为演示方便,我们假定$plugin中至少包含
 #$plugin = array(
 # 'name' => '插件名称',
 # 'directory'=>'插件安装目录'
 #);
 $plugins = get_active_plugins();#这个函数请自行实现
 if($plugins)
 {
  foreach ($plugins as $plugin)
 {//假定每个插件文件夹中包含一个actions.php文件,它是插件的具体实现
 if (@file_exists(STPATH .'plugins/'.$plugin['directory'].'/actions.php'))
 {
 include_once(STPATH .'plugins/'.$plugin['directory'].'/actions.php');
 $class = $plugin['name'].'_actions';
 if (class_exists($class))
 {
 //初始化所有插件
 new $class($this);
 }
 }
 }
 }
 #此处做些日志记录方面的东西
 }
 
 /**
 * 注册需要监听的插件方法(钩子)
 *
 * @param string $hook
 * @param object $reference
 * @param string $method
 */ function register($hook, &$reference, $method)
 {
 //获取插件要实现的方法
 $key = get_class($reference).'->'.$method;
 //将插件的引用连同方法push进监听数组中
 $this->_listeners[$hook][$key] = array(&$reference, $method);
 #此处做些日志记录方面的东西
 }
 /**
 * 触发一个钩子
 *
 * @param string $hook 钩子的名称
 * @param mixed $data 钩子的入参
 * @return mixed
 */ function trigger($hook, $data='')
 {
 $result = '';
 //查看要实现的钩子,是否在监听数组之中
 if (isset($this->_listeners[$hook]) && is_array($this->_listeners[$hook]) && count($this->_listeners[$hook]) > 0)
 {
 // 循环调用开始
 foreach ($this->_listeners[$hook] as $listener)
 {
 // 取出插件对象的引用和方法
 $class =& $listener[0];
 $method = $listener[1];
 if(method_exists($class,$method))
 {
 // 动态调用插件的方法
 $result .= $class->$method($data);
 }
 }
 }
 #此处做些日志记录方面的东西
 return $result;
 }
} 

接下来是一个简单插件的实现 demo _actions。这是一个简单的Hello World插件,用于输出一句话。在实际情况中,say_hello可能包括对数据库的操作,或者是其他一些特定的逻辑。

<?php
/**
* 这是一个Hello World简单插件的实现
*//**
*需要注意的几个默认规则:
* 1. 本插件类的文件名必须是action
* 2. 插件类的名称必须是{插件名_actions}
*/class DEMO_actions
{
 //解析函数的参数是pluginManager的引用
 function __construct(&$pluginManager)
 {
 //注册这个插件
 //第一个参数是钩子的名称
 //第二个参数是pluginManager的引用
 //第三个是插件所执行的方法
 $pluginManager->register('demo', $this, 'say_hello');
 }
 
 function say_hello()
 {
 echo 'Hello World';
 }
} 

再接下来就是插件的调用触发的地方,比如我要将say_hello放到我博客首页Index.php, 那么你在index.php中的某个位置写下:

$pluginManager->trigger('demo',''); 

第一个参数表示钩子的名字,第二个参数是插件对应方法的入口参数,由于这个例子中没有输入参数,所以为空。

这样一个例子基本上很明确的表达了”钩子”插件机制的实现方式和逻辑。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 php自学中心。

感谢阅读!

文章来源:智云一二三科技

文章标题:php中钩子(hook)的原理与简单应用

文章地址:https://www.zhihuclub.com/77580.shtml

关于作者: 智云科技

热门文章

评论已关闭

30条评论

  1. Keeps, a hair loss treatment site for men, is based in New York and has raised nearly 23 million Allo stesso tempo, l azione del Sildenafil termina dopo 5 ore di assunzione della pillola

  2. Where tubal or uterine abnormality was suspected, a hysteroscopy and or laparoscopy was performed.

  3. Both studies found that short course metformin pretreatment resulted in improved response in relation to the control group using clomiphene citrate alone in terms of ovulation and pregnancy rates. Its prevalence is about 1 in the general population and 10 15 in infertile couples.

  4. This model has been used to study several aspects of breast cancer including; initiation, histological and molecular progression, metastasis and, more recently with the rise of immunotherapies, cancer immunology. Gunn- Moore DA, Gruffydd- Jones TJ, Harbour DA.

  5. Waxman, Democrat of California, and Senator Patrick J S IN D R O M E D E C U S H IN G D IA G N O S T IC A D O

  6. Thomas, and K Abdominal and Intramuscular Fat Increase Risk of Heart Disease in Breast Cancer Survivors

  7. In contrast, the genes that did not gain H3K27me3 levels were defined as Ezh2 target Ezh1 no Comp Women who do not exhibit sensitivity to the additional intake of androgens or who are not afraid of possible masculinization symptoms get on well with 2 4 tablets over a period not exceeding 4 6 weeks

  8. The locus specific transcriptional consequences of BET bromodomain inhibitors in hematologic malignancies have recently been elucidated Loven, et al

  9. For trt usage, the ratio is usually 4 1, so this was a clear indication of steroid use Nevertheless, among dozens of anabolic steroids, Anadrol is one of the most effective when it comes to increasing body strength And in one week, Rancic will hit the red carpet to interview some of the most accomplished television celebrities on the red carpet for the 71st Primetime Emmy Awards

  10. When considering all prescriptions that received PAP assistance, the median amount of financial assistance provided by PAPs per prescription was 411

  11. disulfiram will increase the level or effect of bosentan by affecting hepatic enzyme CYP2C9 10 metabolism

  12. Depending on your symptoms, your health care provider may also recommend medication to treat bed bug ailments Kanchwala MD, Stephen J

  13. The best companies will even provide certificates of analysis COA to show that what is in the product matches what is on the label

  14. These findings suggest that HF itself can cause insulin resistance, which may lead to the further exacerbation of HF

  15. Diagnostic algorithm for evaluating cases of potential macrocyclic lactone resistant heartworm However, significant comfort may be derived from the excellent frozen embryo transfer pregnancy rates in this unit

  16. Vascular Oral Only Cycle We investigated the potential mechanisms of tamoxifen cytotoxicity in the U 373, U 138, and U 87 human glioblastoma cell lines, namely interference with protein kinase C PKC activity, the oestrogen receptor, and or the production of transforming growth factor beta 1 TGF beta 1

  17. In men, the most common reasons for infertility are sperm disorders, such as low sperm count, low sperm motility, malformed sperm, and blocked sperm ducts yohimbe decreases effects of promethazine by pharmacodynamic antagonism

  18. This does not sit well with the Boss and thanks to Kinzie, he she manages to break free of his her prison In the United States, the CBC is typically reported in the following format

  19. Because blepharitis is a chronic condition it is very difficult to eliminate the condition for a lifetime

  20. A significant increase of intracellular and secreted protein levels upon TAM exposure whereas, estradiol induced a significant decrease 56

网站地图