根底应用
# 列出所有可用命令php artisan list# 查看命令帮忙php artisan help migrate
编写命令
php artisan make:command SendEmails
# app/Console/Commands/SendEmails.phpnamespace App\Console\Commands;use App\User;use App\DripEmailer;use Illuminate\Console\Command;class SendEmails extends Command{ /** * 命令行的名称及签名 */ protected $signature = 'email:send {user}'; /** * 命令行的形容 */ protected $description = 'Send drip e-mails to a user'; public function __construct() { parent::__construct(); } /** * 命令运行内容 */ public function handle(DripEmailer $drip) { $drip->send(User::find($this->argument('user'))); }}
命令参数和选项
// 必填参数email:send {user}// 可选参数email:send {user?}// 带有默认值的可选参数email:send {user=foo}// 选项,传入即为true,否则为falseemail:send {user} {--queue}// 接管选项值email:send {user} {--queue=}// 选项的默认值email:send {user} {--queue=default}// 选项简写email:send {user} {--Q|queue}// 输出数组;php artisan email:send foo baremail:send {user*}// 选项数组;php artisan email:send --id=1 --id=2email:send {user} {--id=*}// 输出阐明email:send {user : The ID of the user} {--queue= : Whether the job should be queued}
获取输出
$userId = $this->argument('user');$arguments = $this->arguments();$queueName = $this->option('queue');$options = $this->options();
编写输入
# 输入文本$this->line('Display this on the screen');# 输入信息$this->info('Display this on the screen');# 输入谬误$this->error('Something went wrong!');# 输入表格$headers = ['Name', 'Email'];$users = App\User::all(['name', 'email'])->toArray();$this->table($headers, $users);# 输入进度条$users = App\User::all();$bar = $this->output->createProgressBar(count($users));$bar->start();foreach ($users as $user) { $this->performTask($user); $bar->advance();}$bar->finish();
注册命令
# app/Console/Kernel.php// 手动注册命令protected $commands = [ Commands\SendEmails::class];// 主动扫描目录注册命令protected function commands(){ $this->load(__DIR__.'/Commands'); require base_path('routes/console.php');}