tomwright / eventing

此包的最新版本(1.0.0)没有可用的许可信息。

一个简单的事件处理器。

1.0.0 2016-03-23 12:42 UTC

This package is auto-updated.

Last update: 2024-09-15 06:55:34 UTC


README

Build Status Total Downloads Latest Stable Version Latest Unstable Version License

使用方法

您需要一个事件和一个事件处理器。

假设我们有一个事件类,存储在 app/eventing/event/UserWasRegistered.php。

namespace App\Eventing\Event;

class UserWasRegistered extends \TomWright\Eventing\Event\Event
{
	protected $userId;
    
    public function setUserId($userId)
    {
    	$this->userId = $userId;
    }
    
    public function getUserId()
    {
    	return $this->userId;
    }
}

假设我们还有一个事件处理器类,存储在 app/eventing/handler/UserWasRegisteredHandler.php。

namespace App\Eventing\Handler;

class UserWasRegisteredHandler implements \TomWright\Eventing\Listener\ListenerInterface
{   
    public function handle(\TomWright\Eventing\Event\EventInterface $event)
    {
    	echo "User #{$event->getUserId()} has been registered.";
    }
}

现在我们需要添加一个事件处理器/监听器命名空间,这样事件总线才知道在哪里查找处理器。

$bus = \TomWright\Eventing\EventBus::getInstance();
$bus->addListenerNamespace('\\App\\Eventing\\Handler');

现在,每当注册一个新用户时,我们只需要做以下操作

$bus = \TomWright\Eventing\EventBus::getInstance();
$event = new \App\Eventing\Event\UserWasRegistered();
$event->setUserId(123);
$bus->dispatch($event);