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...?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With