Laravel 中的命令行脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40993513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:53:06  来源:igfitidea点击:

Command-line scripts in Laravel?

phplaravel

提问by daninthemix

I have some command line scripts that I would like to modify to use Laravel's features (Eloquent etc).

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

How do I do that? I am aware that Laravel bootstraps from the index.html file. Is there any provision for running command-line apps / scripts?

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

回答by Artur Subotkevi?

  1. Make a command using php artisan make:command FancyCommand.
  2. In /app/Console/Commands/FancyCommand.phpfind a protected variable $signatureand change it's value to your preferred signature:

    protected $signature = 'fancy:command';
    
  3. Code in the handle()method will be executed:

    public function handle()
    {
        // Use Eloquent and other Laravel features...
    
        echo 'Hello world';
    }
    
  4. Register your new command in the /app/Console/Kernel.phpby adding your command's class name to $commandsarray.

    protected $commands = [
        // ...
        Commands\FancyCommand::class,
    ];
    
  5. Run your new command: php artisan fancy:command.

  1. 使用php artisan make:command FancyCommand.
  2. /app/Console/Commands/FancyCommand.php找到一个受保护的变量$signature并将其值更改为您喜欢的签名:

    protected $signature = 'fancy:command';
    
  3. handle()方法中的代码将被执行:

    public function handle()
    {
        // Use Eloquent and other Laravel features...
    
        echo 'Hello world';
    }
    
  4. /app/Console/Kernel.php通过将命令的类名添加到$commands数组中,在 中注册新命令。

    protected $commands = [
        // ...
        Commands\FancyCommand::class,
    ];
    
  5. 运行您的新命令:php artisan fancy:command.

回答by Antonio Carlos Ribeiro

Yes, you can use Artisan commands:

是的,您可以使用 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');
});

Then run it using

然后使用运行它

user@ubuntu: php artisan my:command

Check the docs: https://laravel.com/docs/5.3/artisan

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

You can also use the scheduler: https://laravel.com/docs/5.3/scheduling

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