5.1 事件Event
Minor的 Event
类提供一个简单的观察者实现,允许您在应用程序里订阅与监听事件。
5.1.1 订阅事件
首先创建一个事件类:
<?<span>php namespace App\Event; </span><span>use</span><span> Minor\Event\Event; </span><span>class</span> DemoEvent <span>extends</span><span> Event { </span><span>private</span> <span>$name</span><span>; </span><span>public</span> <span>function</span> __construct(<span>$name</span><span>) { </span><span>$this</span>->name = <span>$name</span><span>; } </span><span>public</span> <span>function</span> setName(<span>$name</span><span>) { </span><span>$this</span>->name = <span>$name</span><span>; } </span><span>public</span> <span>function</span><span> getName() { </span><span>return</span> <span>$this</span>-><span>name; } }</span>
然后在配置文件中注册这个事件:
<?<span>php </span><span>return</span> <span>$events</span> =<span> [ </span>'App\Event\DemoEvent' =><span> [ </span>'App\Listener\DemoListener' => 'handle',<span> ]</span>,<span> ];</span>
5.1.2 触发事件
Minor提供了一个事件管理类:Minor\Event\EventManger,通过调用该类的静态方法fire:EventManager::fire($event)就可以触发这个事件,例:
<span>class</span> FooController <span>extends</span><span> Controller { </span><span>public</span> <span>function</span> bar(<span>$productName</span><span>) { </span><span>$event</span> = <span>new</span> DemoEvent('DemoEvent'<span>); EventManager</span>::fire(<span>$event</span><span>); </span>...<span> } }</span>
5.2 监听器
当触发事件后事件管理器EventManager就会通过配置文件去触发监听器的制定方法。在5.1.1配置文件中我们配置了DemoEvent的监听器为App\Listener\DemoListener的handle方法,可以看一下这个类的实现:
<?<span>php namespace App\Listener; </span><span>use</span><span> App\Event\DemoEvent; </span><span>use</span><span> Minor\Event\Listener; </span><span>class</span> DemoListener <span>extends</span><span> Listener { </span><span>public</span> <span>function</span> handle(DemoEvent <span>$event</span><span>) { </span><span>echo</span> '[DemoListener] handle the event:[' . <span>$event</span>->getName() .'] success!<br/><br/>'<span>; } }</span>