Laravel中的命令行脚本?

dan*_*mix 5 php laravel

我有一些命令行脚本,我想修改以使用Laravel的功能(Eloquent等).

我怎么做?我知道Laravel从index.html文件引导.是否有运行命令行应用程序/脚本的规定?

Art*_*vič 12

  1. php artisan make:command MyCommand.
  2. /app/Console/Commands/MyCommand.php
  3. 找:

    protected $signature = 'command:name';
    
    Run Code Online (Sandbox Code Playgroud)
  4. 改成:

    protected $signature = 'my:command';
    
    Run Code Online (Sandbox Code Playgroud)
  5. handle()方法你可以解雇一些代码:

    public function handle()
    {
        echo 'Hello world';
    }
    
    Run Code Online (Sandbox Code Playgroud)
  6. /app/Console/Kernel.php你会找到受保护的变量$commands.添加Command的类名.

    protected $commands = [
        // ...
        Commands\MyCommand::class,
    ];
    
    Run Code Online (Sandbox Code Playgroud)
  7. php artisan my:command.


Ant*_*iro 7

是的,您可以使用Artisan命令:

Artisan::command('my:command', function () {
    // Here you can use Eloquent
    $user = User::find(1);

    // Or execute shell commands
    $output = shell_exec('./script.sh var1 var2');
});
Run Code Online (Sandbox Code Playgroud)

然后使用它运行它

user@ubuntu: php artisan my:command
Run Code Online (Sandbox Code Playgroud)

查看文档:https://laravel.com/docs/5.3/artisan

您也可以使用调度程序:https://laravel.com/docs/5.3/scheduling