amitmerchant1990 / amitmerchant-dot-com-comments

1 stars 0 forks source link

event-subscribers-laravel/ #73

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Listen to multiple events in a single class in Laravel — Amit Merchant — A blog on PHP, JavaScript, and more

The Observer design pattern is one of the twenty-three well-known “Gang of Four” design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

https://www.amitmerchant.com/event-subscribers-laravel/

yaddly commented 1 year ago

Thank you for your invaluable and educative article. May I implore you to correct your Listener class to the following:

<?php

namespace App\Listeners;

use App\Events\OrderCancelled;

class SendCancellationNotification
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\OrderCancelled  $event
     * @return void
     */
    public function handle(OrderCancelled $event)
    {
        // Access the order using $event->order...
    }
}

This way, you maintain the flow of your example and how the event class in related to the listener class in the above example of cancelling an order without losing your audience.

Kindly point out to readers that when creating a listener, they can optionally specify the event this listener is listening on using this artisan command:

php artisan make:listener SendCancellationNotification --event=OrderCancelled