ogestor / hookable
Laravel Eloquent钩子系统。
v6.0
2020-11-26 17:22 UTC
Requires
- php: >=5.6.4
- illuminate/database: 5.3.*|5.4.*|5.5.*|6.*
Requires (Dev)
- crysalead/kahlan: ~1.1
README
为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规范。