类文档

Hooks

💡 云策文档标注

概述

本文档介绍了 WordPress 中 Hooks 类的核心功能,用于管理事件的注册和分发。该类实现了 HookManager 接口,提供 register 和 dispatch 方法,支持优先级设置和参数传递。

关键要点

  • Hooks 类用于处理钩子的添加和事件分发,是 WordPress 事件系统的关键组件。
  • register 方法用于注册钩子回调函数,支持指定优先级,并包含严格的参数类型验证。
  • dispatch 方法用于触发钩子事件,按优先级顺序执行回调函数,并处理参数数组。
  • __wakeup 方法防止反序列化,确保类实例的安全性。
  • 代码中使用了异常处理来确保参数类型正确,如 InvalidArgument 异常。

代码示例

public function register($hook, $callback, $priority = 0) {
    if (is_string($hook) === false) {
        throw InvalidArgument::create(1, '$hook', 'string', gettype($hook));
    }
    // 更多验证和注册逻辑...
}

public function dispatch($hook, $parameters = []) {
    if (is_string($hook) === false) {
        throw InvalidArgument::create(1, '$hook', 'string', gettype($hook));
    }
    // 更多分发逻辑...
}

注意事项

  • register 方法要求 $hook 为字符串,$callback 为可调用对象,$priority 为整数,否则抛出 InvalidArgument 异常。
  • dispatch 方法要求 $hook 为字符串,$parameters 为数组,并处理参数数组以避免 PHP 8.0 中的键名解释问题。
  • __wakeup 方法抛出 LogicException,防止类被反序列化,确保代码安全。

📄 原文内容

Handles adding and dispatching events

Methods

Name Description
Hooks::__wakeup
Hooks::dispatch Dispatch a message
Hooks::register Register a callback for a hook

Source

class Hooks implements HookManager {
	/**
	 * Registered callbacks for each hook
	 *
	 * @var array
	 */
	protected $hooks = [];

	/**
	 * Register a callback for a hook
	 *
	 * @param string $hook Hook name
	 * @param callable $callback Function/method to call on event
	 * @param int $priority Priority number. <0 is executed earlier, >0 is executed later
	 * @throws WpOrgRequestsExceptionInvalidArgument When the passed $hook argument is not a string.
	 * @throws WpOrgRequestsExceptionInvalidArgument When the passed $callback argument is not callable.
	 * @throws WpOrgRequestsExceptionInvalidArgument When the passed $priority argument is not an integer.
	 */
	public function register($hook, $callback, $priority = 0) {
		if (is_string($hook) === false) {
			throw InvalidArgument::create(1, '$hook', 'string', gettype($hook));
		}

		if (is_callable($callback) === false) {
			throw InvalidArgument::create(2, '$callback', 'callable', gettype($callback));
		}

		if (InputValidator::is_numeric_array_key($priority) === false) {
			throw InvalidArgument::create(3, '$priority', 'integer', gettype($priority));
		}

		if (!isset($this->hooks[$hook])) {
			$this->hooks[$hook] = [
				$priority => [],
			];
		} elseif (!isset($this->hooks[$hook][$priority])) {
			$this->hooks[$hook][$priority] = [];
		}

		$this->hooks[$hook][$priority][] = $callback;
	}

	/**
	 * Dispatch a message
	 *
	 * @param string $hook Hook name
	 * @param array $parameters Parameters to pass to callbacks
	 * @return boolean Successfulness
	 * @throws WpOrgRequestsExceptionInvalidArgument When the passed $hook argument is not a string.
	 * @throws WpOrgRequestsExceptionInvalidArgument When the passed $parameters argument is not an array.
	 */
	public function dispatch($hook, $parameters = []) {
		if (is_string($hook) === false) {
			throw InvalidArgument::create(1, '$hook', 'string', gettype($hook));
		}

		// Check strictly against array, as Array* objects don't work in combination with `call_user_func_array()`.
		if (is_array($parameters) === false) {
			throw InvalidArgument::create(2, '$parameters', 'array', gettype($parameters));
		}

		if (empty($this->hooks[$hook])) {
			return false;
		}

		if (!empty($parameters)) {
			// Strip potential keys from the array to prevent them being interpreted as parameter names in PHP 8.0.
			$parameters = array_values($parameters);
		}

		ksort($this->hooks[$hook]);

		foreach ($this->hooks[$hook] as $priority => $hooked) {
			foreach ($hooked as $callback) {
				$callback(...$parameters);
			}
		}

		return true;
	}

	public function __wakeup() {
		throw new LogicException( __CLASS__ . ' should never be unserialized' );
	}
}