fattureincloud/eloquence-hookable

Laravel Eloquent 钩子系统。

v8.0.2 2024-08-29 13:29 UTC

This package is auto-updated.

Last update: 2024-08-29 13:30:20 UTC


README

stable

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