Laravel中的命令行脚本?

时间:2016-12-06 10:49:29

标签: php laravel

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

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

2 个答案:

答案 0 :(得分:9)

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

    protected $signature = 'command:name';
    
  4. 更改为:

    protected $signature = 'my:command';
    
  5. 那里有handle()方法可以解雇一些代码:

    public function handle()
    {
        echo 'Hello world';
    }
    
  6. /app/Console/Kernel.php中,您会找到受保护的变量$commands。添加您的Command的类名。

    protected $commands = [
        // ...
        Commands\MyCommand::class,
    ];
    
  7. 运行php artisan my:command

答案 1 :(得分: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');
});

然后使用

运行它
user@ubuntu: php artisan my:command

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

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