Skip to content

Latest commit

 

History

History
81 lines (60 loc) · 1.17 KB

event.md

File metadata and controls

81 lines (60 loc) · 1.17 KB

Event

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.

  1. Dispatch event
$event = new UserCreatedEvent(1);
\K::dispatch("user.created", $event);
  1. Define event
class UserCreatedEvent
{
    const NAME = "user.created";
    
    /**
     * User id
     *
     * @var integer
     */
    public $id;
    
    public function __construct($id)
    {
        $this->id = $id;
    }
}
  1. Listener
# bootstrap.php

\K::addEventListener(UserCreatedEvent::NAME, function (UserCreatedEvent $event) {
    // handle user event
});
  1. Start
$ bin/mqk --bootstrap bootstrap.php

Subscriber

  1. Define subscriber
class UserSubscriber
{
    /**
     * @Listener(UserCreatedEvent::NAME)
     */
    public function onCreated(UserCreatedEvent $event)
    {
        // 处理用户创建事件
    }
}
  1. Subscribe

Specify bootstrap in the configuration file and add the subscribers to bootstrap '.

# bootstrap.php

\K::addSubscriber(new UserSubscriber());
  1. Start
$ bin/mqk --bootstrap bootstrap.php