为什么和何时应该使用命令总线而不是控制器Laravel?

4

laravel 5 中新增的命令总线特性让我感到困惑。为什么我们可以在控制器中完成相同的任务,而需要使用命令呢?

命令(Command)

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))
      );
  }
}

Why should I make it complex, while I can straight away do it in controller rather than using command.

2个回答

5
这个想法来自“命令模式”,其中使用对象封装信息以执行操作。
使用命令模式可以更轻松地组织软件中要执行的动作。作为对象的命令可在多个控制器中重复使用,从而让您DRY(不要重复自己)。
由于命令对象与控制器解耦,因此更易于测试。
当然,在编程中存在权衡。使用命令模式时,您需要更多的类(和文件)。 因此,在需要时才使用它。 当您发现要执行复杂操作且控制器开始变得庞大时,也许您会想看看这种模式。

1
您不必使用命令。这完全取决于您的项目规模。如果您可以通过将内容放入控制器中来摆脱它,那就这样做。这里没有法律,只有好坏实践。而被认为是良好实践的东西并不总是您正在构建的最佳选择。
正如您所说,为什么要让它变得复杂呢?不要这样做。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接