- Commands are things about to happen right now. i.e. "CreateUser"
- Events are things that have just occured right now - i.e. "UserSuccessfullyCreated"
这些差异看起来很小,但也有一些关键的差异.
- Commands must be specifically called/dispatched. I.e. if you want to
do CommandX - you must call CommandX somewhere.
- 事件respond到应用程序中的事件触发anywhere.
让我们举个例子来最好地说明这一点.假设我们创建了一个用户,我们希望向他们发送一封欢迎邮箱,并更新我们的通讯列表.
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
}
但如果我们使用事件,我们会在CommandClass中执行类似的操作
public function handle(CreateUser $auth)
{
// 1. Create the user here
Event::fire(new UserWasCreated($user));
}
然后,我们可以根据需要创建任意多个事件,并执行以下操作:
EventClassA
Event::listen('UserWasCreated', function($event)
{
// 2. Send welcome email
});
EventClassB
Event::listen('UserWasCreated', function($event)
{
// 3. Update our newsletter
});
最大的好处是分离关注点."createuser"命令现在不需要担心创建用户后会发生什么.它只需要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.