PHP code example of kode / console

1. Go to this page and download the library: Download kode/console library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kode / console example snippets




use Kode\Console\Command;
use Kode\Console\Input;
use Kode\Console\Output;

class HelloCommand extends Command
{
    public function __construct()
    {
        parent::__construct(
            'hello',                           // 命令名
            '输出问候语',                       // 描述
            'hello {name?} {--upper:bool}'    // 签名
        );
        
        $this->sig($this->usage);
    }

    public function fire(Input $in, Output $out): int
    {
        $name = $in->arg(0, 'World');
        $upper = $in->flag('upper');
        
        $greeting = "Hello, {$name}!";
        
        if ($upper) {
            $greeting = strtoupper($greeting);
        }
        
        $out->success($greeting);
        
        return 0; // 返回 0 表示成功
    }
}



ode\Console\Kernel;

$kernel = new Kernel();
$kernel->add(HelloCommand::class);

exit($kernel->boot($argv));

// 获取位置参数
$name = $in->arg(0, 'default');

// 获取选项值
$port = $in->opt('port');

// 检查标志
$verbose = $in->flag('v');

// 类型转换
$port = $in->cast($in->opt('port'), 'int');

// 参数验证
$valid = $in->validate('port', $port, ['

// 询问用户输入
$name = Input::ask('请输入名称', '默认名称');

// 确认操作
if (Input::confirm('确定要删除吗?', false)) {
    // 执行删除
}

// 选择选项
$choice = Input::choice('请选择环境', [
    'dev' => '开发环境',
    'prod' => '生产环境',
], 'dev');

// 基础输出
$out->line('普通文本');
$out->info('信息文本');
$out->warn('警告文本');
$out->error('错误文本');
$out->success('成功文本');

// 带颜色输出
$out->line('红色文本', 'red');
$out->line('加粗文本', 'bold');

// 表格输出
$out->table(['ID', '名称', '状态'], [
    ['ID' => 1, '名称' => '张三', '状态' => '活跃'],
    ['ID' => 2, '名称' => '李四', '状态' => '离线'],
]);

// 进度条
for ($i = 0; $i <= 100; $i++) {
    $out->progress($i, 100);
    usleep(50000);
}

// JSON 输出
$out->json(['status' => 'ok', 'data' => $result]);

use Kode\Console\CommandGroup;

// 创建命令组
$databaseGroup = new CommandGroup('database', '数据库操作');
$databaseGroup->addCommand(new MigrateCommand());
$databaseGroup->addCommand(new SeedCommand());

$kernel->addGroup($databaseGroup);

use Kode\Console\Contract\IsMiddleware;

class TimingMiddleware implements IsMiddleware
{
    public function handle(Input $in, Output $out, callable $next): int
    {
        $start = microtime(true);
        
        $result = $next($in, $out);
        
        $duration = round((microtime(true) - $start) * 1000, 2);
        $out->line("\n执行时间: {$duration}ms", 'gray');
        
        return $result;
    }
}

$kernel->addMiddleware(new TimingMiddleware());

use Kode\Console\EventManager;
use Kode\Console\Event;

$eventManager = new EventManager();

// 监听事件
$eventManager->listen('command.executing', function (Event $event) {
    echo "即将执行: {$event->data['command']->name}\n";
});

$kernel->setEventManager($eventManager);

class ServeCommand extends Command
{
    public function __construct()
    {
        parent::__construct('serve', '启动开发服务器', 'serve {port?} {--host=localhost}');
        $this->sig($this->usage);
        
        // 添加别名
        $this->alias(['server', 'start']);
        
        // 添加示例
        $this->example('serve', '在当前目录启动服务器');
        $this->example('serve 8080 --host=0.0.0.0', '指定端口和主机启动');
        
        // 设置相关命令
        $this->related(['migrate', 'seed']);
        
        // 设置分组
        $this->group('development');
    }
}
bash
php console.php hello John
# 输出: Hello, John!

php console.php hello --upper
# 输出: HELLO, WORLD!

kode/console
├── Command.php             # 命令基类
├── Kernel.php              # 控制台内核
├── Input.php               # 输入解析器
├── Output.php              # 输出封装
├── Signature.php           # 签名解析器
├── Event.php               # 事件类
├── EventManager.php        # 事件管理器
├── CommandGroup.php        # 命令分组
├── Contract/               # 接口定义
│   ├── IsCommand.php
│   ├── IsInput.php
│   ├── IsOutput.php
│   ├── IsKernel.php
│   ├── IsEvent.php
│   ├── IsEventManager.php
│   └── IsMiddleware.php
├── Helper/                 # 工具类
│   └── Reflector.php
├── Middleware/             # 中间件
│   └── LoggingMiddleware.php
└── Listener/               # 监听器
    └── CommandLogger.php
bash
composer analyse