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
Command-line scripts in Laravel?
提问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?
- Make a command using
php artisan make:command FancyCommand
. In
/app/Console/Commands/FancyCommand.php
find a protected variable$signature
and change it's value to your preferred signature:protected $signature = 'fancy:command';
Code in the
handle()
method will be executed:public function handle() { // Use Eloquent and other Laravel features... echo 'Hello world'; }
Register your new command in the
/app/Console/Kernel.php
by adding your command's class name to$commands
array.protected $commands = [ // ... Commands\FancyCommand::class, ];
Run your new command:
php artisan fancy:command
.
- 使用
php artisan make:command FancyCommand
. 在
/app/Console/Commands/FancyCommand.php
找到一个受保护的变量$signature
并将其值更改为您喜欢的签名:protected $signature = 'fancy:command';
handle()
方法中的代码将被执行:public function handle() { // Use Eloquent and other Laravel features... echo 'Hello world'; }
/app/Console/Kernel.php
通过将命令的类名添加到$commands
数组中,在 中注册新命令。protected $commands = [ // ... Commands\FancyCommand::class, ];
运行您的新命令:
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