沙发/可挂载

Laravel Eloquent 插件系统。

v7.0.1 2020-12-05 07:21 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 规范