phutureproof/hookable

Laravel Eloquent 钩子系统。

dev-master 2023-02-01 10:41 UTC

This package is not auto-updated.

Last update: 2024-09-26 16:15:48 UTC


README

GitHub Tests Action Status stable Downloads

Eloquent ORM (Laravel 5.2)提供的钩子系统。

以下方法都提供了钩子

  • Model::getAttribute
  • Model::setAttribute
  • Model::save
  • Model::toArray
  • Model::replicate
  • Model::isDirty
  • Model::__isset
  • Model::__unset

以及 Illuminate\Database\Eloquent\Builder 类上的所有方法。

安装

克隆存储库或将其作为 composer 依赖项拉取

composer require sofa/hookable:~5.2

用法

为了注册一个钩子,你需要在模型上使用静态方法 hook示例

重要 由于 PHP 不允许在 静态上下文(例如模型的 boot 方法)中创建时将 Closure 绑定到你的模型实例,因此你需要稍微修改一下,即在对象上下文中创建闭包。

例如,请参阅上面的示例以及用于那里封装我们的闭包的类

钩子闭包的签名如下

function (Closure $next, mixed $payload, Sofa\Hookable\Contracts\ArgumentBag $args)

钩子通过 Sofa\Hookable\Pipeline 按照它们注册的顺序解决(除了 setAttribute,那里的顺序是相反的),并且除非你提前返回,否则会调用每个钩子

// example hook on getAttribute method:
function ($next, $value, $args)
{
    if (/* your condition */) {
        // return early
        return 'some value'; // or the $value
    }

    else if (/* other condition */) {
        // you may want to mutate the value
        $value = strtolower($value);
    }

    // finally continue calling other hooks
    return $next($value, $args);
}

贡献

欢迎所有贡献,PR 必须经过 测试 并符合 PSR-2 规范。