如何做一个PHP钩子系统? [英] How to do a PHP hook system?
本文介绍了如何做一个PHP钩子系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在PHP应用程式中使用钩子系统,以便在执行前后更改程式码。一个hookloader类的基本架构将如何用于PHP CMS(甚至是一个简单的应用程序)。
How do you impliment a hook system in a PHP application to change the code before or after it executes. How would the basic architecture of a hookloader class be for a PHP CMS (or even a simple application). How then could this be extended into a full plugins/modules loader?
(另外,CMS挂钩系统上是否有任何书籍或教程?)
(Also, are there any books or tutorials on a CMS hook system?)
推荐答案
You can build an events system as simple or complex as you want it.
/**
* Attach (or remove) multiple callbacks to an event and trigger those callbacks when that event is called.
*
* @param string $event name
* @param mixed $value the optional value to pass to each callback
* @param mixed $callback the method or function to call - FALSE to remove all callbacks for event
*/
function event($event, $value = NULL, $callback = NULL)
{
static $events;
// Adding or removing a callback?
if($callback !== NULL)
{
if($callback)
{
$events[$event][] = $callback;
}
else
{
unset($events[$event]);
}
}
elseif(isset($events[$event])) // Fire a callback
{
foreach($events[$event] as $function)
{
$value = call_user_func($function, $value);
}
return $value;
}
}
添加活动
event('filter_text', NULL, function($text) { return htmlspecialchars($text); });
// add more as needed
event('filter_text', NULL, function($text) { return nl2br($text); });
// OR like this
//event('filter_text', NULL, 'nl2br');
然后这样调用
$text = event('filter_text', $_POST['text']);
或删除该事件的所有回调,例如
Or remove all callbacks for that event like this
event('filter_text', null, false);
这篇关于如何做一个PHP钩子系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文