laravel 5中包含的新命令总线特性让我感到困惑。当我们可以在控制器本身中实现相同的任务时,为什么以及何时应该使用命令?
命令
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));
}
}
控制器use IlluminateFoundationBusDispatchesCommands;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;
use PurchasePodcast;
abstract class Controller extends BaseController {
use DispatchesCommands, ValidatesRequests;
public function purchasePodcast($podcastId)
{
$this->dispatch(
new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId))
);
}
}
为什么我要让它变得复杂,而我可以直接在控制器中做,而不是使用命令。
这个想法来自"命令模式",其中一个对象被用来封装执行操作的信息。
使用命令模式可以更容易地组织在软件中执行的操作。命令作为一个对象,可以在多个控制器中重用,因此可以DRY (Don't Repeat Yourself)。
Command对象也更容易测试,因为它与控制器解耦了。
当然,在编程中存在权衡。当您使用命令模式时,您将拥有更多的类(和文件)。所以,需要的时候就用吧。当你发现一个复杂的动作要执行,而你的控制器开始变胖,也许你想看看这个模式。
您不必使用命令。这完全取决于你项目的规模。如果你可以在控制器上放东西,那就这么做吧。这里没有法律,只有好的/坏的习惯。被认为是好的实践并不总是你正在构建的最好的选择。
就像你说的,为什么要把它弄复杂?没有。