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);

相关文章