命令行工具

最后更新: 2026-01-27 11:02:47

命令行工具

Unicode Framework 提供了强大的命令行工具系统,支持自定义命令和参数解析。

命令行基础

运行命令

<h1 id="查看帮助">查看帮助</h1>
php console
php console --help
php console -h

<h1 id="运行命令">运行命令</h1> php console <command> [arguments] [options]

<h1 id="示例">示例</h1> php console api:doc index php console api:doc index --output docs/api.json

命令格式

php console <command> [arguments] [--options]

创建命令

基本命令类

namespace App\Console\Commands;

use Unicode\Framework\Console\Command;

class HelloCommand extends Command { protected string $name = 'hello'; protected string $description = 'Say hello';

public function handle(array $arguments, array $options): int { $name = $arguments[0] ?? 'World'; echo "Hello, {$name}!\n"; return 0; } }

注册命令

use App\Console\Commands\HelloCommand;
use Unicode\Framework\Console\Console;

$console = new Console(); $console->register(new HelloCommand());

命令接口

namespace App\Console\Commands;

use Unicode\Framework\Interfaces\CommandInterface;

class CustomCommand implements CommandInterface { public function getName(): string { return 'custom'; }

public function getDescription(): string { return 'Custom command description'; }

public function handle(array $arguments, array $options): int { // 命令逻辑 return 0; } }

命令参数

位置参数

class GreetCommand extends Command
{
    protected string $name = 'greet';
    protected string $description = 'Greet someone';

public function handle(array $arguments, array $options): int { $name = $arguments[0] ?? 'Guest'; $greeting = $arguments[1] ?? 'Hello';

echo "{$greeting}, {$name}!\n"; return 0; } }

// 使用 // php console greet John Hi // 输出: Hi, John!

选项参数

class CreateUserCommand extends Command
{
    protected string $name = 'user:create';
    protected string $description = 'Create a new user';

public function handle(array $arguments, array $options): int { $name = $options['name'] ?? $arguments[0] ?? null; $email = $options['email'] ?? $arguments[1] ?? null;

if (!$name || !$email) { echo "Error: Name and email are required\n"; echo "Usage: php console user:create --name=John --email=john@example.com\n"; return 1; }

// 创建用户 db('users')->insert([ 'name' => $name, 'email' => $email, ]);

echo "User created successfully!\n"; return 0; } }

// 使用 // php console user:create --name=John --email=john@example.com // 或 // php console user:create --name John --email john@example.com

布尔选项

class MigrateCommand extends Command
{
    protected string $name = 'migrate';
    protected string $description = 'Run database migrations';

public function handle(array $arguments, array $options): int { $force = isset($options['force']) || isset($options['f']); $seed = isset($options['seed']) || isset($options['s']);

// 运行迁移 if ($force) { // 强制运行 }

if ($seed) { // 运行种子数据 }

return 0; } }

// 使用 // php console migrate --force --seed // 或 // php console migrate -f -s

内置命令

API 文档生成

<h1 id="生成-api-文档">生成 API 文档</h1>
php console api:doc <app-name> [options]

<h1 id="选项">选项</h1> <h1 id="output--o-输出文件路径">--output, -o: 输出文件路径</h1> <h1 id="title-文档标题">--title: 文档标题</h1> <h1 id="version-api-版本">--version: API 版本</h1> <h1 id="description-文档描述">--description: 文档描述</h1> <h1 id="base-url-api-基础-url">--base-url: API 基础 URL</h1>

<h1 id="示例">示例</h1> php console api:doc index --output docs/api.json --title "API Documentation"

队列 Worker

<h1 id="启动队列-worker">启动队列 Worker</h1>
php console queue:work [options]

<h1 id="选项">选项</h1> <h1 id="queue-指定队列名称">--queue: 指定队列名称</h1> <h1 id="connection-指定连接">--connection: 指定连接</h1> <h1 id="processes-进程数">--processes: 进程数</h1> <h1 id="max-jobs-最大任务数">--max-jobs: 最大任务数</h1> <h1 id="max-time-最大运行时间秒">--max-time: 最大运行时间(秒)</h1> <h1 id="timeout-任务超时时间秒">--timeout: 任务超时时间(秒)</h1> <h1 id="memory-内存限制mb">--memory: 内存限制(MB)</h1>

<h1 id="示例">示例</h1> php console queue:work --queue=high-priority --processes=4

路由缓存

<h1 id="清除路由缓存">清除路由缓存</h1>
php console route:clear

<h1 id="生成路由缓存">生成路由缓存</h1> php console route:cache

任务调度

<h1 id="运行调度器">运行调度器</h1>
php console schedule:run

<h1 id="列出计划任务">列出计划任务</h1> php console schedule:list

命令输出

标准输出

class InfoCommand extends Command
{
    public function handle(array $arguments, array $options): int
    {
        echo "This is a message\n";
        echo "Multiple lines\n";
        echo "of output\n";
        return 0;
    }
}

错误输出

class ErrorCommand extends Command
{
    public function handle(array $arguments, array $options): int
    {
        fwrite(STDERR, "Error: Something went wrong\n");
        return 1;
    }
}

格式化输出

class TableCommand extends Command
{
    public function handle(array $arguments, array $options): int
    {
        $users = db('users')->get();

echo "ID\tName\tEmail\n"; echo str_repeat('-', 50) . "\n";

foreach ($users as $user) { echo "{$user['id']}\t{$user['name']}\t{$user['email']}\n"; }

return 0; } }

命令交互

读取输入

class InteractiveCommand extends Command
{
    public function handle(array $arguments, array $options): int
    {
        echo "Enter your name: ";
        $name = trim(fgets(STDIN));

echo "Hello, {$name}!\n"; return 0; } }

确认操作

class DeleteCommand extends Command
{
    public function handle(array $arguments, array $options): int
    {
        $id = $arguments[0] ?? null;

if (!$id) { echo "Error: ID is required\n"; return 1; }

echo "Are you sure you want to delete user {$id}? (yes/no): "; $confirm = trim(fgets(STDIN));

if ($confirm !== 'yes') { echo "Cancelled.\n"; return 0; }

db('users')->where('id', $id)->delete(); echo "User deleted.\n"; return 0; } }

最佳实践

1. 命令命名

// ✅ 推荐:使用命名空间风格
class UserCreateCommand extends Command
{
    protected string $name = 'user:create';
}

class UserDeleteCommand extends Command { protected string $name = 'user:delete'; }

// ❌ 错误:使用不清晰的命名 class CreateCommand extends Command { protected string $name = 'create'; // 不清晰 }

2. 参数验证

// ✅ 推荐:验证参数
class CreateUserCommand extends Command
{
    public function handle(array $arguments, array $options): int
    {
        $name = $arguments[0] ?? null;
        $email = $arguments[1] ?? null;

if (!$name || !$email) { echo "Error: Name and email are required\n"; echo "Usage: php console user:create <name> <email>\n"; return 1; }

// 验证邮箱格式 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Error: Invalid email format\n"; return 1; }

// 创建用户 return 0; } }

3. 错误处理

// ✅ 推荐:正确处理错误
class ProcessCommand extends Command
{
    public function handle(array $arguments, array $options): int
    {
        try {
            // 执行操作
            processData();
            echo "Success!\n";
            return 0;
        } catch (\Exception $e) {
            echo "Error: {$e->getMessage()}\n";
            return 1;
        }
    }
}

4. 进度显示

// ✅ 推荐:显示处理进度
class ImportCommand extends Command
{
    public function handle(array $arguments, array $options): int
    {
        $file = $arguments[0];
        $data = file($file);
        $total = count($data);

foreach ($data as $index => $line) { processLine($line);

$progress = round(($index + 1) / $total * 100, 2); echo "\rProgress: {$progress}% ({$index + 1}/{$total})"; }

echo "\nDone!\n"; return 0; } }

5. 命令组织

// ✅ 推荐:按功能组织命令
namespace App\Console\Commands;

// 用户相关命令 class UserCreateCommand extends Command { } class UserDeleteCommand extends Command { } class UserListCommand extends Command { }

// 数据库相关命令 class MigrateCommand extends Command { } class SeedCommand extends Command { }

常见问题

Q: 如何查看所有可用命令?

A: 运行 php consolephp console --help

Q: 如何传递多个参数?

A: 使用空格分隔:php console command arg1 arg2 arg3

Q: 如何传递包含空格的参数?

A: 使用引号:php console command "arg with spaces"

Q: 如何获取选项值?

A: 使用 $options['option-name'] 获取选项值。

Q: 命令返回值有什么意义?

A: 返回 0 表示成功,非 0 表示失败。

相关文档