JosephLavin / local-eventing
对象事件执行
1.0.1
2016-08-14 19:49 UTC
Requires
- php: 5.6.0
- tightenco/collect: ^5.2
Requires (Dev)
- phpunit/phpunit: ^5.5
This package is not auto-updated.
Last update: 2024-09-24 22:50:49 UTC
README
这是一个简单的PHP特质,允许以事件驱动的方式执行本地方法。按照命名约定将方法添加到使用此特质的类中,当本地事件被触发时,它们将被执行。
use josephlavin\localEventing\LocalEventing; class dummy { use LocalEventing; public function save() { // do your saving logic... $this->fireLocalEvent('saved'); } protected function __onLocalEvent_saved_send_notification() { // Logic here to send notification... } protected function __onLocalEvent_saved_log_event() { // Logic for logging here... } }
事件监听器方法命名约定
所有事件监听器方法都必须按照以下方式命名:__onLocalEvent_[事件]_[描述]()
__onLocalEvent_
:本地事件系统的命名空间[事件]
:与$this->fireLocalEvent('事件')
中给出的相同字符串[描述]
:此方法所做操作的简单描述
安装
$ composer require josephlavin/local-eventing
用例
假设我们有一个基本的模型类型类,它可以触发本地事件
class BaseModel { use LocalEventing; public function __construct() { $this->fireLocalEvent('created'); } public function insert() { $this->fireLocalEvent('preInsert'); // the insert logic... $this->fireLocalEvent('postInsert'); } }
我们可以创建另一个特质,它依赖于LocalEventing特质,并添加__onLocalEvent__
方法。注意,这个特质有一个抽象方法_require_trait_LocalEventing
。这作为对开发者的提醒,表明这个特质依赖于LocalEventing特质才能正确工作。
trait UuidPrimaryKey { // reminder that we must also use LocalEventing Trait abstract protected function _require_trait_LocalEventing(); protected function __onLocalEvent_preInsert_populate_uuid() { // generate and set a uuid primary key here... } }
现在,任何模型(扩展基本模型)都可以使用UuidPrimaryKey特质并获取该功能。
class MyModel extends BaseModel { use UuidPrimaryKey; }