larabel Artisan Command 使用总结
定义命令
Artisan::command('ltf', function () {
(new AppServicesEditService())->edit();
$this->comment("news sent");
})->describe('Send news');
//调用
> php artisan ltf
- 通过artisan make:command来自动生成(以SendEmails为例)
- php artisan make:command SendEmails 会在app/Console/Commands下创建SendEmails.php 文件
- 编写SendEmails 类和调用
use IlluminateConsoleCommand;
use Redis;
class SendEmails extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
//这里必须要填 格式是[命令名] [name参数] [选项参数]
//调用示例 php artisan ltf:ltftest aaa --que
protected $signature = 'ltf:ltftest {name}{--que}';
/**
* The console command description.
*
* @var string
*/
//这里是命令描述
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
// handle 方法在命令执行时被调用,将所有命令逻辑都放在这个方法里面。
public function handle()
{
Redis::set('ttttt','dass');
}
}
命令参数获取
$this->argument('name'); //返回某个参数的值
$this->arguments(); //返回所有参数,数组格式
// 获取指定选项...
$queueName = $this->option('queue');
// 获取所有选项...
$options = $this->options();
命令行交互
public function handle(){
$name = $this->ask('What is your name?');
}
public function handle(){
$name = $this->secret('What is your password?');
}
public function handle(){
$this->confirm('Do you wish to continue? [y|N]')
}
public function handle(){
$name = $this->choice('What is your name?', ['Taylor', 'Dayle']);
}
public function handle(){
$this->info('Display this on the screen');
$this->error('Display this on the screen');
$this->line('Display this on the screen');
}
public function handle(){
$headers = ['Name', 'Email'];
$users = AppUser::all(['name', 'email'])->toArray();
$this->table($headers, $users);
}
代码调用命令
Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1, '--queue' => 'default'
]);
});
Route::get('/foo', function () {
Artisan::queue('email:send', [
'user' => 1, '--queue' => 'default'
]);
});
/**
* 执行控制台命令
*
* @return mixed
*/
public function handle(){
$this->call('email:send', [
'user' => 1, '--queue' => 'default'
]);
}