Skip to main content

Module console

Module console 

Source
Expand description

Console 模块 — 自定义命令注册与分发

对齐 PHP ThinkPHP 6 think\console\Consolethink\console\Command 基类。

§PHP 对齐

PHP ThinkPHP 通过 think\console\Console 注册并分发命令:

$console = new \think\Console();
$console->add(new \app\command\Hello());
$console->run();

Rust 端通过 Console 结构体 + Command trait 实现等价功能:

use sz_rust_cli::{Console, Command, CommandSignature};

struct HelloCommand;

impl Command for HelloCommand {
    fn signature(&self) -> CommandSignature {
        CommandSignature {
            name: "hello".to_string(),
            description: "Print hello world".to_string(),
            usage: "sz-rust hello".to_string(),
        }
    }
    fn execute(&self, _args: &[String]) -> Result<i32, sz_rust_cli::CliError> {
        println!("Hello, World!");
        Ok(0)
    }
}

let mut console = Console::new();
console.register(Box::new(HelloCommand));
console.run(std::env::args().collect()).await;

§设计说明

  • 内置命令(make / migrate / route / cache / scheduler)仍由 clap derive 处理
  • 自定义命令通过 Command trait 在运行时注册
  • Console::run 先检查首个参数是否匹配已注册的自定义命令,若不匹配则回退到 clap CLI

Structs§

CommandSignature
控制台命令签名(名称、描述、用法)
Console
控制台应用 — 命令注册表与分发器

Traits§

Command
自定义控制台命令 trait