Why and when should I use command bus vs controller laravel?

The inclusion of the command line feature in laravel 5 scares me. Why and when should I use commands while we can achieve the same task in the controller itself?

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, even though I can immediately do it in the controller and not use a command.

+3


source to share


2 answers


The idea comes from the "Command Pattern" in which an object is used to encapsulate information to perform an action.

Using the Command pattern can make it easier to organize actions in software. A command, as an object, can be reused across multiple controllers, so you can use DRY (don't repeat yourself).



The command object is also easier to test because it is separate from the controller.

There is, of course, a programming tradeoff. By using the command template, you will have more classes (and files). So use it when you need it. When you find a complex action to take and your controller starts to grow, you might want to take a look at this pattern.

+5


source


You don't need to use commands. It all depends on the size of your project. If you can get away with putting in your controller, do it. There is no law here, only good / bad practices. And what counts as good practice is not always the best option for what you are building.



Why is it difficult as you said? Do not do that.

+1


source







All Articles