lkt/hooks

LKT Hooks 引擎

1.0.0 2023-07-11 15:11 UTC

This package is auto-updated.

Last update: 2024-09-24 13:58:49 UTC


README

安装

composer require lkt/hooks

注册钩子

use Lkt\Hooks\Hook;

Hook::register('hook-name', 'hook-action', [callable])

例如

use Lkt\Hooks\Hook;

Hook::register('create-user', 'mail-set-up-password', [callable])
Hook::register('create-user', 'mail-admin-new-user-created', [callable])

每个操作都可以注册多次。当触发时,将返回所有结果。

唯一的限制是所有动作处理程序必须具有相同的方法定义。

例如

class HookStack {

    public static function mailPassword(int $userId, string $name, string $lastname): bool
    {
        // ... your stuff
        return true;
    }

    // If we want to define another method with different code,
    // the method must have the same arguments and return type.
    // This is a valid method:
    public static function mailPassword2(int $userId, string $name, string $lastname): bool
    {
        // ... another stuff
        return true;
    }

    // This is an invalid method:
    public static function mailPassword3(int $userId, string $name): bool
    {
        // ... third stuff
        return true;
    }
}
use Lkt\Hooks\Hook;

Hook::register('create-user', 'mail-set-up-password', [HookStack::class, 'mailPassword'])
Hook::register('create-user', 'mail-set-up-password', [HookStack::class, 'mailPassword2'])
Hook::register('create-user', 'mail-set-up-password', [HookStack::class, 'mailPassword3'])

触发钩子

use Lkt\Hooks\Hook;

Hook::run('hook-name', ...$args)

例如

use Lkt\Hooks\Hook;

$id = 1;
$name = 'John';
$lastname = 'Doe';

$response = Hook::register('create-user', $id, $name, $lastname);

前面的例子将返回一个包含所有触发调用结果的 HookResponse 对象。