## Mix Event
參考 PHP PSR-14 標準的事件調度庫
Event dispatch library refer to PHP PSR-14 standard
> 該庫還有 php 版本:https://github.com/mix-php/event
## Overview
事件調度是一種常見機制,允許開發人員輕松,一致地將邏輯注入應用程序,這在 PHP 中非常常見,于是我打造了這個 Go 版本的事件調度庫,整體實現基于 [PSR-14](https://www.php-fig.org/psr/psr-14/):
- 事件(Event):一個自定義結構體,事件數據的載體
- 監聽器(Listener):負責處理對應的事件數據
- 事件調度器(Dispatcher):用于觸發某個事件
## Installation
- 安裝
```
go get -u github.com/mix-go/event
```
## Usage
定義事件 `Event`,事件可以為任意結構體,只需要繼承 `event.EventTrait` 即可
```
type CommandBeforeExecuteEvent struct {
event.EventTrait
Command interface{}
}
```
定義監聽器 `Listener`,監聽器是用戶編寫處理事件邏輯代碼的地方,`Events` 方法返回一個要監聽的事件類的數組,當這些事件觸發時,會調用 `Process` 方法:
```
type CommandListener struct {
}
func (t *CommandListener) Events() []event.Event {
return []event.Event{
&event2.CommandBeforeExecuteEvent{},
}
}
func (t *CommandListener) Process(e event.Event) {
switch e.(type) {
case *event2.CommandBeforeExecuteEvent:
// 初始化全局對象
globals.Init()
// 設置守護
if flag.Match("d", "daemon").Bool() {
process.Daemon()
}
break
}
}
```
觸發某個事件 `Dispatcher`
```
e := &CommandBeforeExecuteEvent{
Command: "foo",
}
d := event.NewDispatcher(&CommandListener)
d.Dispatch(e)
```
## License
Apache License Version 2.0, http://www.apache.org/licenses/