flexpress/component-hooks

该包最新版本(v1.0.0)没有可用的许可信息。

WordPress 钩子系统助手

v1.0.0 2014-08-13 13:19 UTC

This package is not auto-updated.

Last update: 2024-09-24 03:49:12 UTC


README

通过 pimple 安装

在我们做其他任何事情之前,我们需要在 pimple 中设置配置

$pimple['configHookable'] = function() {
  return new Config();
};

$pimple['hooker'] = function ($c) {
  return new Hooker($c['objectStorage'], array(
    $c['configHookable']
  ));
};

我们在这里做了两件事,创建了一个用于钩子的配置和一个用于可钩子类的配置,然后将配置Hookable传递给钩子,以便它可以连接其所有钩子。

请注意,$c['objectStorage'] 是 SPLObjectStorage 类。

设置钩子

要添加钩子,我们首先需要创建一个使用 HookableTrait 的类,让我们创建一个非常基本的类来完成这个任务

class Config {

  use HookableTrait;

}

简单,已经完成,但我们应该可能添加一个钩子方法,让我们现在就做

class Config {

  use HookableTrait;
  
  /**
   * @type action
   */
  public function adminInit() {
    echo "Hello, this is the admin hook being fired";
  }

}

此示例为配置类添加了一个钩子,为 action admin_init 添加了 adminInit 函数,注意方法名是驼峰式。

除了设置动作外,您还可以添加过滤器,如下所示

class Config {

  use HookableTrait;
  
  /**
   * @type action
   */
  public function adminInit() {
    echo "Hello, this is the admin hook being fired";
  }
  
  /**
   * @type filter
   */
  public function theTitle($title) {
    return strip_tags($title);
  }

}

在此示例中,我们通过挂钩 the_title 过滤器添加了一个从标题中删除标签的过滤器。

因此,对于过滤器,您只需将此添加到方法上方的方法注释中

/**
 * @type action
 */

对于过滤器,您做同样的事情,但将类型更改为 filter

/**
 * @type filter
 */

高级用法

除了指定钩子类型外,您还可以指定优先级,如下所示

/**
 * @type action
 * @priority 10
 */

最后,您还可以指定期望的参数数量,如下所示

/**
 * @type action
 * @priority 10
 * @params 3
 */

这允许您添加动作和过滤器钩子,指定优先级以及期望的参数数量,因此没有从 add_action 和 add_filter 函数中删除任何内容。

公共方法 - Hooker

  • hookUp() - 遍历传递给钩子的所有可钩子并连接它们。

公共方法 - HookableTrait

  • hookUp() - 使用反射查找所有具有有效文档块的方法,并将它们连接起来。

受保护的方法 - HookableTrait

  • getMethodAttributes() - 获取方法文档块的所有属性。
  • getHookName($methodName, $attributes) - 对于给定方法名和属性,获取钩子名称。例如,theContent 变为 the_content
  • registerHook($hook_name, $method_name, $attributes) - 根据类型实际注册钩子。