W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
創(chuàng)建一個(gè)新命令后,你應(yīng)該先修改 signature
和 description
屬性以便你在使用 Artisan 命令 list
時(shí)能夠清楚知道該命令的用法。執(zhí)行命令時(shí)會(huì)調(diào)用 handle
方法,你可以在此方法中放置命令邏輯。
技巧:為了實(shí)現(xiàn)更好的代碼復(fù)用,請(qǐng)盡量讓你的命令類保持輕量并且能夠延遲到應(yīng)用服務(wù)中完成。在下面的例子中,我們將注入一個(gè)服務(wù)類來完成發(fā)送郵件的重任。
來看一個(gè)簡(jiǎn)單的例子。在命令類的 handle
方法中,我們可以注入任何我們需要的依賴項(xiàng)。Laravel 服務(wù)容器 將會(huì)自動(dòng)注入所有在構(gòu)造函數(shù)中帶類型約束的依賴。
<?php
namespace App\Console\Commands;
use App\Models\User;
use App\Support\DripEmailer;
use Illuminate\Console\Command;
class SendEmails extends Command
{
/**
* 命令名稱及簽名
*
* @var string
*/
protected $signature = 'email:send {user}';
/**
* 命令描述
*
* @var string
*/
protected $description = 'Send drip e-mails to a user';
/**
* 創(chuàng)建命令
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* 執(zhí)行命令
*
* @param \App\Support\DripEmailer $drip
* @return mixed
*/
public function handle(DripEmailer $drip)
{
$drip->send(User::find($this->argument('user')));
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: