laravel:编写命令行脚本(10.27.0)

发布时间 2023-10-23 08:35:02作者: 刘宏缔的架构森林

 一,相关文档

https://learnku.com/docs/laravel/10.x/artisan/14859

二,php代码

1,创建command

liuhongdi@lhdpc:/data/laravel/dignews$ php artisan make:command Cart

   INFO  Console command [app/Console/Commands/Cart.php] created successfully.

2,command的代码:

app/Console/Commands/Cart.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
 
namespace App\Console\Commands;
 
use Illuminate\Console\Command;
 
class Cart extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:cart {userId} {--fromdate=} {--enddate=}';
 
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '清理购物车中的过期商品';
 
    /**
     * Execute the console command.
     */
    public function handle()
    {
        //
        echo "打印参数";
        print_r($this->arguments());
        echo "打印选项m";
        print_r($this->options());
 
        $userId = $this->argument('userId');
        echo "userId:".$userId."\n";
        $fromDate = $this->option('fromdate');
        echo "fromDate:".$fromDate."\n";
        $endDate = $this->option('enddate');
        echo "endDate:".$endDate."\n";
 
    }
}

三,测试效果:

1,打印参数

liuhongdi@lhdpc:/data/laravel/dignews$ php artisan app:cart 123 --fromdate="2020-01-01" --enddate="2022-12-31"
打印参数Array
(
    [command] => app:cart
    [userId] => 123
)
Array
(
    [fromdate] => 2020-01-01
    [enddate] => 2022-12-31
    [help] => 
    [quiet] => 
    [verbose] => 
    [version] => 
    [ansi] => 
    [no-interaction] => 
    [env] => 
)
userId:123
fromDate:2020-01-01
endDate:2022-12-31

2,打印帮助

liuhongdi@lhdpc:/data/laravel/dignews$ php artisan help app:cart
Description:
  清理购物车中的过期商品

Usage:
  app:cart [options] [--] <userId>

Arguments:
  userId                     

Options:
      --fromdate[=FROMDATE]  
      --enddate[=ENDDATE]    
  -h, --help                 Display help for the given command. When no command is given display help for the list command
  -q, --quiet                Do not output any message
  -V, --version              Display this application version
      --ansi|--no-ansi       Force (or disable --no-ansi) ANSI output
  -n, --no-interaction       Do not ask any interactive question
      --env[=ENV]            The environment the command should run under
  -v|vv|vvv, --verbose       Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

四,查看laravel框架的版本:

liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0