What is the difference between commands and events in the context of Laravel 5?

advertisements

So Laravel 5 was finally released yesterday with the final implementation of the command bus but I was wandering, what's the real difference in using a command bus over event mechanisms that we have in the previous releases?

Ok, I see the reason that it can be used to create commands from Request objects which is pretty useful but beyond that it seems to behave in a similar way even down to the whole queuing functionality for events now?

Can you please provide examples of use cases and where the pros and cons of either are?


  • Commands are things about to happen right now. i.e. "CreateUser"
  • Events are things that have just occured right now - i.e. "UserSuccessfullyCreated"

The differences appear minor - but have some key differences.

  • Commands must be specifically called/dispatched. I.e. if you want to do CommandX - you must call CommandX somewhere.
  • Events respond to an event firing anywhere in your application. The great thing is multiple event handling classes can respond to the same event.

Lets do an example to illustrate it best. Lets say we create a user, and we want to send them a welcome email and also update our newsletter list.

In a Command Scenario would would do

AdminController {

    function create() {
            Bus::dispatch(new CreateUser(Auth::user());
    }
}

then in our CommandClass - we would do

public function handle(CreateUser $auth)
{
     // 1. Create the user here
     // 2. Send welcome email
     // 3. Update our newsletter
}

But if we use events - we would do something like this in our CommandClass

public function handle(CreateUser $auth)
    {
         // 1. Create the user here
         Event::fire(new UserWasCreated($user));
    }

then we can create as many events as we want to listen to that event and do something:

EventClassA

Event::listen('UserWasCreated', function($event)
{
    // 2. Send welcome email
});

EventClassB

Event::listen('UserWasCreated', function($event)
{
    // 3. Update our newsletter
});

The great thing is separation of concerns. The command "createuser" now does not need to worry itself about what happens after a user is created. It just needs to CreateUser.

Also - if we want to add another function after a user signs up - say enter them in a lotto draw - you can just add another Event Class and add a new event listener.

EventClassC

Event::listen('UserWasCreated', function($event)
{
    // 4. Register them in lotto
});

Notice how we didnt need to touch the command CreateUser class code at all? This provides a true separation concerns of classes in a OOP style approach.