Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

naming Laravel events, listeners and Jobs

I have an event called UserWasRegistered also I have a listener called UserWasRegistered from there I intned to develop job commands called:

EmailRegistrationConfirmation

NotifyAdminsNewRegistration

CreateNewBillingAccount

All these jobs would be executed within the UserWasRegistered event listener class.

Is this the correct approach or should i just have multiple listeners for UserWasRegistered? I feel using the jobs approach enabled me to call those "jobs" from other areas in my application at different times. e.g. calling CreateNewBillingAccount might be called if a user changed their details...?

like image 848
AndrewMcLagan Avatar asked Feb 08 '16 04:02

AndrewMcLagan


1 Answers

I recommend to change the listener names that's more explicit about what's happening, so I'd avoid directly pairing listeners with events.

We're using an anemic event/listener approach, so listeners pass the actual task to "doers" (jobs, services, you name it).

This example is taken from a real system:

app/Providers/EventServiceProvider.php:

    OrderWasPaid::class    => [
        ProvideAccessToProduct::class,
        StartSubscription::class,
        SendOrderPaidNotification::class,
        ProcessPendingShipment::class,
        LogOrderPayment::class
    ],

StartSubscription listeners:

namespace App\Modules\Subscription\Listeners;


use App\Modules\Order\Contracts\OrderEventInterface;
use App\Modules\Subscription\Services\SubscriptionCreator;

class StartSubscription
{
    /**
     * @var SubscriptionCreator
     */
    private $subscriptionCreator;

    /**
     * StartSubscription constructor.
     *
     * @param SubscriptionCreator $subscriptionCreator
     */
    public function __construct(SubscriptionCreator $subscriptionCreator)
    {
        $this->subscriptionCreator = $subscriptionCreator;
    }

    /**
     * Creates the subscription if the order is a subscription order.
     *
     * @param OrderEventInterface $event
     */
    public function handle(OrderEventInterface $event)
    {
        $order = $event->getOrder();

        if (!$order->isSubscription()) {
            return;
        }

        $this->subscriptionCreator->createFromOrder($order);
    }
}

This way you can invoke jobs/services (SubscriptionCreator in this example) in other areas of your application.

It's also possible to bind the listener to other events as well, other than OrderWasPaid.

like image 106
Attila Fulop Avatar answered Sep 19 '22 17:09

Attila Fulop