laravel 5.7控制台测试如何创建Artisan :: command()

时间:2018-12-13 10:42:08

标签: laravel

嗨,在哪里放置这段代码,它一定是类之类的东西,否则我将不得不生成文件以及如何执行该文件?

Artisan::command('question', function () {
    $name = $this->ask('What is your name?');

    $language = $this->choice('Which language do you program in?', [
        'PHP',
        'Ruby',
        'Python',
    ]);

    $this->line('Your name is '.$name.' and you program in '.$language.'.');
}); 

1 个答案:

答案 0 :(得分:0)

您有2个选择。

第一个选项:在控制台路由文件(routes / console.php)中

Artisan::command('question', function () { 

    $name = $this->ask('What is your name?');

    $language = $this->choice('Which language do you program in?', [
        'PHP',
        'Ruby',
        'Python',
    ]);

    $this->line('Your name is '.$name.' and you program in '.$language.'.');

});

第二个选项:创建命令类

php artisan make:command QuestionCommand

然后将逻辑放在handle()方法中:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class QuestionCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'question';

    /**
     * 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
     */
    public function handle()
    {
        $name = $this->ask('What is your name?');

        $language = $this->choice('Which language do you program in?', [
            'PHP',
            'Ruby',
            'Python',
        ]);

        $this->line('Your name is '.$name.' and you program in '.$language.'.');
    }
}