An event is a tool for decoupling between services in a microarchitecture. Using MQK events, you can respond to an event and execute a piece of code in the listener.
- Dispatch event
$event = new UserCreatedEvent(1);
\K::dispatch("user.created", $event);
- Define event
class UserCreatedEvent
{
const NAME = "user.created";
/**
* User id
*
* @var integer
*/
public $id;
public function __construct($id)
{
$this->id = $id;
}
}
- Listener
# bootstrap.php
\K::addEventListener(UserCreatedEvent::NAME, function (UserCreatedEvent $event) {
// handle user event
});
- Start
$ bin/mqk --bootstrap bootstrap.php
- Define subscriber
class UserSubscriber
{
/**
* @Listener(UserCreatedEvent::NAME)
*/
public function onCreated(UserCreatedEvent $event)
{
// 处理用户创建事件
}
}
- Subscribe
Specify bootstrap
in the configuration file and add the subscribers to bootstrap
'.
# bootstrap.php
\K::addSubscriber(new UserSubscriber());
- Start
$ bin/mqk --bootstrap bootstrap.php