菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
48
0

自定义 Artisan 命令

原创
05/13 14:22
阅读数 871

1. 生成新的 Artisan 命令

运行下面的命令会生成 app/Console/Commands/{YourCommandName}.php 文件

php artisan make:command YourCommandName

Artisan 命令的默认架构

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class YourCommandName extends Command
{
    /**
     * The name and signature of the console command.
     * 这个属性的值是命令的名称 ,比如现在是 command:name ,那么调用命令的格式就是 php artisan command:name
     *
     * @var string
     */
    protected $signature = 'command:name';

    /**
     * The console command description.
     * 这个属性是命令的描述信息 ,使用 php artisan help command:name 查看命令帮助信息时 ,会显示这个值
     * 
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * 这个函数是调用命令时执行的操作
     *
     * @return mixed
     */
    public function handle()
    {
        // 现在执行这个命令就会写一个 /test artisan 的文件 ,内容是 test
        file_put_contents('/test artisan', 'test');
    }
}

2. 注册和调用命令

想要使用上面创建的命令 ,还需要注册这个命令 ,有两种方式

2.1 app/Console/Kernel.php

在 app/Console/Kernel.php 的 $commands 属性下新增刚刚创建的命令即可

/**
 * The Artisan commands provided by your application.
 *
 * @var array
 */
protected $commands = [
    //
    \App\Console\Commands\YourCommandName::class
];

然后就可以执行这个命令了

php artisan command:name

2.2 基于闭包的命令

// routes/console.php
Artisan::command('password:reset {userId} {--sendEmail}', function(){
    // 第一个参数是命令的名称
    // 执行一些操作 ,比如重置用户密码 ...
})

3. 参数和选项

以下面这个名称为例 ,来讲解 Artisan 命令的语法

protected $signature = 'password:reset {userId} {--sendEmail}';

3.1 参数

格式 说明
password:reset {userId} 用大括号将必须的参数包起来
password:reset {userId?} 可选参数加个问号
password:reset {userId=1} 默认值参数

3.2 选项

选项和参数类似 ,但是要加前缀 -- ,并且也可以不赋值

格式 说明
password:reset {userId} {--sendEmail} 普通选项
password:reset {userId} {--password=} 多一个 "=" 号 ,可以为选项赋值
password:reset {userId} {--queue=default} 默认值选项

3.3 参数数组和选项数组

参数和选项中如果要使用数组加一个 "*" 号

格式 说明
password:reset {userIds*} 参数数组
password:reset {--ids=*} 选项数组

Artisan 命令中使用数组

# 参数
php artisan password:reset 1 2 3
# 选项
php artisan password:reset --ids=1 --ids=2 --ids=3

4. 描述信息

// 前面提到过 $description 是命令的描述信息
protected $description = 'Command description';

还需要一些参数和选项的描述信息

protected $signature = 'password:reset {userId : 用户的 ID} {--sendEmail : 是否向用户发送邮件 1=发送 0=不发送}';

使用 artisan help 来查看这个命令的帮助信息

php artisan help password:reset
Description:
  Command description

Usage:
  password:reset [options] [--] <userId>

Arguments:
  userId                用户的 ID

Options:
      --sendEmail       是否向用户发送邮件 1=发送 0=不发送
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable 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

5. 使用 handle()

5.1 argument()

/**
 * Execute the console command.
 * 这个函数是调用命令时执行的操作
 *
 * @return mixed
 */
public function handle()
{
    // 定义 :password:reset {userId}
    // 执行 :php artisan password:reset 5

    $this->argument(); // 返回一个包含所有参数的数组( 第一个元素是命令名称 )
    // [
    //     "command" => "password:reset",
    //     "userId" => "5"
    // ]

    $this->argument('userId');
    // "5"
}

5.2 option()

/**
 * Execute the console command.
 * 这个函数是调用命令时执行的操作
 *
 * @return mixed
 */
public function handle()
{
    // 定义 :password:reset {--userId=}
    // 执行 :php artisan password:reset --userId=5

    $this->option(); // 返回一个包含所有选项的数组
    // [
    //     "userId" => "5",
    //     "help" => false,
    //     "quiet" => false,
    //     "verbose" => false,
    //     "version" => false,
    //     "ansi" => false,
    //     "no-interaction" => false,
    //     "env" => null
    // ]
    $this->option('userId');
    // "5"
}

5.3 交互式输入信息

在 handle() 中还有一些用于与用户交互的方法

// 提示用户输入
$email = $this->ask("你的邮箱是什么?");

// 提示用户输入 ,但用 "*" 隐藏输入内容
$password = $this->secret("你的数据库密码是什么?");

// 提示用户输入是 / 否 ,返回布尔值 ,除了按 y 和 Y ,其他的输入都会返回 false
if ($this->confirm("你确定要重置用户的密码?"));

// 提示用户选择选项 ,如果用户没有选择 ,默认值就是最后一个选项
$tips = '你希望在每天什么时间备份数据库?'
$options = array("08:00", "20:00", "12:00");
$default = 0;
$index = $this->choice($tips, $options, $default);
// 这里注意返回的是用户选择的 key ,而不是 value
print_r($optios[$index]);

// 还可以使用关联数组
$tips = '你现在有两个选择';
$options = array("a" => "自己脱", "b" => "我帮你脱");
$default = "b";
$index = $this->choice($tips, $options, $default);
print_r($optios[$index]);

5.4 向用户提示信息

$this->info("默认颜色的文字");
$this->comment("橙色的文字");
$this->question("青色的文字");
$this->error("红色的文字");
$this->line("没有颜色的文字");

5.5 输出数据表

$headers = array('name', 'email');
$data = array(
    array('马云', 'jack_ma@aliyun.com'),
    array('马化腾', 'pony@qq.com')
);
// $data = App\User::all(['name', 'email'])->toArray();
$this->table($headers, $data);
+--------+--------------------+
| name   | email              |
+--------+--------------------+
| 马云   | jack_ma@aliyun.com |
| 马化腾 | pony@qq.com        |
+--------+--------------------+

5.6 进度条

// 将进度条分为 10 份
$total = 10;
// 创建进度条
$this->output->progressStart($total);
// 循环
for ($i = 0; $i < $total; $i++) {
    sleep(1);
    // 进度条步进
    $this->output->progressAdvance();
}
// 结束进度条
$this->output->progressFinish();
# 2
2/10 [=====>----------------------]  20%
# 10
10/10 [============================] 100%

6. 编程式调用

可以用 Artisan facade 或者 Artisan::call() 来调用

也可以用 Artisan::queue() 将命令放到队列中

// Artisan::call()
Route::get('test-artisan', function () { 
    $exitCode = Artisan::call("password:reset", [
        'userId' => 15, '--sendEmail' => true
    ])
})
// $this->call() 或者 $this->callSilent()
Route::get('test-artisan', function () { 
    // 这个 callSilent() 有什么区别我也不太懂
    $exitCode = $this->callSilent("password:reset", [
        'userId' => 15, '--sendEmail' => true
    ])
})
本作品采用《CC 协议》,转载必须注明作者和本文链接

发表评论

0/200
48 点赞
0 评论
收藏
为你推荐 换一批