cooda/php-hooks

钩子系统。

dev-master 2021-05-29 21:35 UTC

This package is auto-updated.

Last update: 2024-09-29 06:02:21 UTC


README

安装PHP-Hooks

推荐通过Composer来安装Hook。

composer require cooda/php-hooks

用法

<?php

use Cooda\Hooks\HookBus;

$hookBus = new HookBus();

$hookBus->hook('some_hook_name')->add(function (&$arg1, &$arg2) {
    $arg1 += 1;
    $arg2 .= ' world';
});

$hookBus->hook('some_hook_name')->add(function (&$arg1, &$arg2) {
    $arg1 += 1;
    $arg2 .= '!';
});

$hookBus->hook('some_hook_name')->add(function (&$arg1, &$arg2) {
    $arg1 += 1;
    $arg2 = "[".$arg2."]";
});

[$arg1, $arg2] = $hookBus->hook('some_hook_name')->do(1, 'Hello');

echo $arg1 . "\n";
echo $arg2;

输出

4
[Hello world!]

Cooda\Hooks\HookBus

hook($tag = null): Hook
  • $tag - 钩子名称。

Cooda\Hooks\Hook

// Add callback to hook.

add(callable $callback, float $priority = Hook::DEFAULT_PRIORITY, string $name = null)
  • $callback - 当钩子被调用时需要调用的回调函数。
  • $priority - 用于指定与特定钩子相关联的函数执行的顺序(默认:10)。数字越小,执行越早,具有相同优先级的函数按它们被添加到操作的顺序执行。
  • $name - 回调名称。
// Call hook.

do(...$args)
  • $args - 将传递给回调函数的参数。
// Remove callback.

remove($callback, float $priority = Hook::DEFAULT_PRIORITY)
  • $callback
  • $priority

辅助工具

<?php

hook('some_hook_name')->add(function () { echo 1; });
hook('some_hook_name')->add(function () { echo 2; });
hook('some_hook_name')->add(function () { echo 3; });
hook('some_hook_name')->do();
/*
Outputs:
123
*/

//chaining
hook('some_hook_name')
    ->add(function () { echo 1; })
    ->add(function () { echo 2; })
    ->add(function () { echo 3; })
    ->do();
/*
Outputs:
123
*/