php _call_hook,php中的钩子(hook插件机制)

hook插件机制的基本思想:

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

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

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

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

2>注册所有插件。

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

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

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

wordpress的hook类实例

6ac5847bb71917fc09bacb35999b189b.png

hook类代码:

class Hook

{

//action hooks array

private static $actions = array();

/**

* ads a function to an action hook

* @param $hook

* @param $function

*/

public static function add_action($hook,$function)

{

$hook=mb_strtolower($hook,CHARSET);

// create an array of function handlers if it doesn't already exist

if(!self::exists_action($hook))

{

self::$actions[$hook] = array();

}

// append the current function to the list of function handlers

if (is_callable($function))

{

self::$actions[$hook][] = $function;

return TRUE;

}

return FALSE ;

}

/**

* executes the functions for the given hook

* @param string $hook

* @param array $params

* @return boolean true if a hook was setted

*/

public static function do_action($hook,$params=NULL)

{

$hook=mb_strtolower($hook,CHARSET);

if(isset(self::$actions[$hook]))

{

// call each function handler associated with this hook

foreach(self::$actions[$hook] as $function)

{

if (is_array($params))

{

call_user_func_array($function,$params);

}

else

{

call_user_func($function);

}

//cant return anything since we are in a loop! dude!

}

return TRUE;

}

return FALSE;

}

/**

* gets the functions for the given hook

* @param string $hook

* @return mixed

*/

public static function get_action($hook)

{

$hook=mb_strtolower($hook,CHARSET);

return (isset(self::$actions[$hook]))? self::$actions[$hook]:FALSE;

}

/**

* check exists the functions for the given hook

* @param string $hook

* @return boolean

*/

public static function exists_action($hook)

{

$hook=mb_strtolower($hook,CHARSET);

return (isset(self::$actions[$hook]))? TRUE:FALSE;

}

}

/**

* Hooks Shortcuts not in class

*/

function add_action($hook,$function)

{

return Hook::add_action($hook,$function);

}

function do_action($hook)

{

return Hook::do_action($hook);

}

使用方法:

//添加钩子

Hook::add_action('unique_name_hook','some_class::hook_test');

//或使用快捷函数添加钩子:

add_action('unique_name_hook','other_class::hello');

add_action('unique_name_hook','some_public_function');

//执行钩子

do_action('unique_name_hook');//也可以使用 Hook::do_action();

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值