建立命令

2018-02-24 15:52 更新

使用 make:command 這個(gè) Artisan 命令可以產(chǎn)生一個(gè)新的命令類 :

php artisan make:command PurchasePodcast

新產(chǎn)生的類會(huì)被放在 app/Commands 目錄中,命令默認(rèn)包含了兩個(gè)方法:構(gòu)造器和 handle 。當(dāng)然,handle 方法執(zhí)行命令時(shí),你可以使用構(gòu)造器傳入相關(guān)的對象到這個(gè)命令中。例如:

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

}

handle 方法也可以使用類型提示依賴,并且通過 服務(wù)容器 機(jī)制自動(dòng)進(jìn)行依賴注入。例如:

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle(BillingGateway $billing)
    {
        // Handle the logic to purchase the podcast...
    }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號