hbroker91 / php-hookifier
轻松添加生命周期钩子的包
1.0.1
2019-11-18 17:50 UTC
Requires
- php: ^7.0
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-19 04:33:35 UTC
README
简单包,可轻松向任何PHP类添加生命周期钩子。
该包由两个文件组成,一个接口和一个特性(混入)。在前者的情况下,类必须实现接口提供的方法;在后者的情况下,它只需将代码混入类的代码库中。
这个小包的主要目的是,在类的实例化之前或销毁之后(或两者之间)添加一个或两个交互点。在允许应用程序进一步执行之前检查各种先决条件是有用的,例如在调用类的构造函数以实例化它之前检查请求数据。
要求
- PHP >= 7.0
- 面向对象编程风格
- 愿意牺牲几个CPU周期 :)
安装
composer require hbroker91/php-hookifier
使用
在需要钩子的类中实现Hookable
接口,或使用Hookify
特性与use
关键字。
示例
namespace Some\Namespace; use Hbroker91\PHPHookifier\Hookable; class UserModel extends Model implements Hookable { /** @var string */ private $userName; /** @var string */ private $userId; /** @var string */ private $emailAddress; ... // if the func. evaluates to false, throw an Exception somewhere at application's boot // otherwise allow this class to instantiate and potentially fill up with data // (in this case this class represents a model). public static function beforeConstruct(... $options): bool { [$payload] = $options; return isset($payload['userData'])); } public static function afterDestroy(... $options): bool { // do some very important thing // if it went ok, return true otherwise false return true; } }
使用trait
类似,例如
namespace Some\Namespace; use Hbroker91\PHPHookifier\Hookify; class UserModel extends Model { use Hookify; /** @var string */ private $userName; /** @var string */ private $userId; /** @var string */ private $emailAddress; ... // if the func. evaluates to false, throw an Exception somewhere at application's boot // otherwise allow this class to instantiate and potentially fill up with data // (in this case this class represents a model). public static function beforeConstruct(... $options): bool { [$payload] = $options; return isset($payload['userData'])); } public static function afterDestroy(... $options): bool {} }
在这种情况下,afterDestroy
的主体为空,它没有使用。
非常直接。
脚注
如果你觉得它有用,请给个⭐,谢谢。
有问题、想法、改进建议吗?
随时联系我。