php - 为什么以及何时应该使用命令总线与 Controller laravel?

标签 php laravel laravel-5

laravel 5 中包含的新命令总线功能让我感到困惑。 为什么以及何时应该使用命令,而我们可以在 Controller 本身中完成相同的任务?

命令

class PurchasePodcast extends Command implements SelfHandling {

protected $user, $podcast;

   /**
   * Create a new command instance.
   *
   * @return void
   */
   public function __construct(User $user, Podcast $podcast)
   {
       $this->user = $user;
       $this->podcast = $podcast;
   }

  /**
    * Execute the command.
    *
    * @return void
    */
    public function handle()
    {
       // Handle the logic to purchase the podcast...

        event(new PodcastWasPurchased($this->user, $this->podcast));
    }

}

Controller

use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use PurchasePodcast;

abstract class Controller extends BaseController {

   use DispatchesCommands, ValidatesRequests;

   public function purchasePodcast($podcastId)
   {
      $this->dispatch(
         new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId))
      );
  }
}

我为什么要让它变得复杂,而我可以直接在 Controller 中完成它而不是使用命令。

最佳答案

这个想法来自“命令模式”,其中使用对象来封装信息以执行 Action 。

使用命令模式可以更轻松地组织要在软件中执行的操作。该命令作为一个对象,可在多个 Controller 中重复使用,因此让您 DRY(不要重复自己)。

命令对象也更容易测试,因为它与 Controller 解耦。

当然,在编程方面需要权衡。使用命令模式时,您将拥有更多的类(和文件)。所以,在你需要的时候使用它。当您发现要执行一个复杂的操作,并且您的 Controller 开始变胖时,也许您会想看看这个模式。

关于php - 为什么以及何时应该使用命令总线与 Controller laravel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31446961/

相关文章:

php - 我如何使用 php 设置文本区域的值?

php - Windows : #1045 - Access denied for user 'root' @'localhost' (using password: YES) phpmyadmin

php - 如何忽略包含 php 的第一行?

validation - Laravel验证PDF MIME

laravel - 如何在laravel nova中为一个字段添加自定义验证和消息

php - 如何在PHP中使用WHERE中的if语句编写sql查询

Laravel 5.0.* 中间件在处理路由之前从 url 中删除前缀语言环境

mysql - 查询 Laravel 中的 MySQL 错误混合非法排序规则

laravel-5 - 在单个页面上处理多个表单

jquery - Toastr 没有出现在 Laravel 5.4 中