bionicmaster/hookable

Laravel Eloquent 钩子系统。

5.4.1 2017-05-27 15:48 UTC

This package is auto-updated.

Last update: 2024-09-14 03:35:56 UTC


README

Build 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 兼容