Using PSR-14 Events with the EventManager - HL Vanilla Community
<main> <article class="userContent"> <p>PHP defines PSR-14 for event dispatching. This is implemented using Vanilla's <code class="code codeInline" spellcheck="false" tabindex="0">\Garden\EventManager::dispatch()</code> and Vanilla's <code class="code codeInline" spellcheck="false" tabindex="0">\Garden\PsrEventHandlersInterface</code>.</p><h2 data-id="dispatching-an-event">Dispatching an Event</h2><p>First get an instance of the <code class="code codeInline" spellcheck="false" tabindex="0">EventManager</code> by dependency injecting it.</p><pre class="code codeBlock" spellcheck="false" tabindex="0">public function __construct(\Garden\EventManager $eventManager) { $this->eventManager = $eventManager; } </pre><p>Alternatively in legacy code you may access it with <code class="code codeInline" spellcheck="false" tabindex="0">\Gdn::eventManager()</code>.</p><p>Next we need to create a class for the event. PSR-14 events don't require any particular interface. You should use this class to define whatever particular logic you may need. A common use of PSR-14 events in Vanilla is events extending <code class="code codeInline" spellcheck="false" tabindex="0">Garden\Events\ResourceEvent</code> which is encodes data about CRUD operations on various resources.</p><p>These events are used to send out webhooks and update elastic search.</p><pre class="code codeBlock" spellcheck="false" tabindex="0">namespace Vanilla\MyAddon\Events; class MyEvent { // Define any of your own logic here. } </pre><p>Finally dispatch it.</p><pre class="code codeBlock" spellcheck="false" tabindex="0">$event = new Vanilla\MyAddon\Events\MyEvent($param1, $param2); // If you need data back from the things handling the event, you can add methods // On your event class to store or set it. $handledEvent = $this->eventManager->dispatch($event); </pre><h2 data-id="handling-events">Handling Events</h2><p>Create an event handler class in the <code class="code codeInline" spellcheck="false" tabindex="0">Addon</code> namespace of your addon.</p><p><strong>/plugins/other-addon/Addon/OtherAddonEventHandlers.php</strong></p><pre class="code codeBlock" spellcheck="false" tabindex="0">namespace Vanilla\OtherAddon\Addon; use Vanilla\MyAddon\Events\MyEvent; class OtherAddonEventHandlers implements \Garden\PsrEventHandlersInterface { public static function getPsrEventHandlerMethods(): array { return ['handleMyEvent']; } public function handleMyEvent(MyEvent $event): MyEvent { // Do something with the event // Return the event for other handlers or the dispatcher. return $event; } } </pre><h2 data-id="tips-for-high-quality-events">Tips for High Quality Events</h2><ul><li>Add strongly typed methods for constructing, modifying, and getting data out of your event.</li><li>Don't forget to return the event from your handlers.</li></ul><p><br></p> </article> </main>