sofa-support/hookable

Laravel Eloquent 钩子系统。

dev-master 2023-07-05 13:19 UTC

This package is auto-updated.

Last update: 2024-09-05 16:03:35 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 不允许您在创建实例时将 Closure 绑定到您的模型实例(例如模型的 boot 方法),因此您需要稍作修改,即在对象上下文中创建闭包。

例如,请参见上面的示例以及 封装我们的闭包的类,该类在该示例中使用。

钩子闭包的签名如下

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 规范。