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/