t-rack-in / 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 不允许你在静态上下文中将 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 规范。