昨天,Laravel 5终于发布了命令总线的最终实现,但我想知道,在之前的版本中,使用命令总线而不是事件机制的真正区别是什么?

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?

你能提供用例的例子,以及两者的优缺点吗?

推荐答案

  • 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.

Laravel相关问答推荐

try 编写一个函数,如果产品存在,则无法删除特定类别

Inertiajs - 使用链接组件添加记录但无法在不使用表单的情况下清除文本区域

将 ID 传递给资源控制器进行编辑

根据路径的开头重定向

无法在 Laravel 项目中安装 @vitejs/plugin-vue

Laravel 5 - 更改模型文件位置

Laravel 5.4 - 如何为同一个自定义验证规则使用多个错误消息

Laravel 5.3 auth 判断构造函数返回 false

如何使用 ajax 请求删除 laravel 5.3 中的记录?

Laravel Electron邮件验证模板位置

Laravel 生产问题 - 使用 Laravel 4.1.x 更新composer

Homebrew PHP 似乎没有链接

Auth 在 Laravel Tinker 中不起作用

Laravel 在特定文件夹中创建迁移文件

从 Artisan 电话中获得响应

laravel 4:更新行时如何从列的当前值中减一?

日期验证 - 如何本地化/翻译字符串今天和明天

如何在 laravel 中使用 GROUP_CONCAT

在 Laravel 中结合 AND/OR Eloquent的查询

[Vue 警告]:找不到元素:#app