ceopag / hookable
Laravel Eloquent 钩子系统。
5.6
2018-03-03 02:55 UTC
Requires
- php: >=5.6.4
- illuminate/database: ^5.3
Requires (Dev)
- crysalead/kahlan: ~1.1
README
为 Laravel 5.2 的 Eloquent ORM 提供钩子系统。
以下方法都提供了钩子:
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 规范。