larabel Artisan Command 使用总结

larabel Artisan Command 使用总结

定义命令
  • 在routes/console.php下定义命令
Artisan::command('ltf', function () {
    (new \App\Services\EditService())->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 Illuminate\Console\Command;
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 = App\User::all(['name', 'email'])->toArray();
$this->table($headers, $users);
}

enter image description here

代码调用命令
  • 路由方式调用
Route::get('/foo', function () {
    $exitCode = Artisan::call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);
});
  • queue调用
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'
    ]);
}
posted @ 2018-12-25 15:53  技术-刘腾飞  阅读(1879)  评论(0编辑  收藏  举报