initphp/console 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

initphp/console

Composer 安装命令:

composer require initphp/console

包简介

A simple helper library for writing console/CLI applications in PHP, including a styleable ANSI table renderer (formerly initphp/cli-table).

README 文档

README

A small, dependency-free helper library for writing console / CLI applications in PHP — command routing, typed arguments, coloured output, interactive questions and a styleable ANSI table renderer.

CI Latest Stable Version Total Downloads License PHP Version Require

Starting with 2.1 this package also ships the ANSI table renderer that used to be distributed as the separate initphp/cli-table package (now deprecated). See Migrating from initphp/cli-table.

Features

  • Command routing — register commands as closures or as classes extending Command.
  • Grouped help — automatic help / list overview and per-command --help usage.
  • Typed arguments — declare --name arguments with a type (INT, FLOAT, BOOL, …), a default and an optional/required flag; values are validated automatically.
  • Input parsing — long arguments (--name=value), short options (-v, -abc, -k=value) and bare positional segments, with automatic scalar type casting.
  • Coloured output — 16/256-colour SGR helpers, message styles (error, success, warning, info), key/value lists and a progress bar.
  • Interactive prompts — free-form ask() and option-constrained question().
  • Table rendering — a styleable, multibyte-aware ASCII/ANSI table.
  • Testable I/O — output and input streams are injectable, so commands can be unit tested without touching STDOUT/STDIN.

Requirements

  • PHP 7.2 or higher
  • ext-mbstring (optional) — improves table alignment for multibyte (UTF-8) values

Installation

composer require initphp/console

Quick start

Create an entry script (e.g. console.php):

#!/usr/bin/env php
<?php

require_once __DIR__ . '/vendor/autoload.php';

use InitPHP\Console\{Application, Input, Output};

$console = new Application('My Console Application', '1.0.0');

// A closure command:  php console.php hello --name=John
$console->register('hello', function (Input $input, Output $output) {
    $output->writeln('Hello {name}!', [
        'name' => $input->getArgument('name', 'World'),
    ]);
}, 'Says hello.');

$console->run();

Run it:

php console.php hello --name=John   # Hello John!
php console.php hello               # Hello World!
php console.php list                # Show all registered commands

Terminology

This library distinguishes three kinds of tokens that follow the command name:

Token Shape Accessor
Argument --name, --name=value getArgument()
Option -v, -abc, -key=value getOption()
Segment bare value, e.g. migrate getSegment()

Note: here --long tokens are called arguments and -short tokens are called options. This is the opposite of some other frameworks — keep it in mind when porting code.

All scalar values are cast automatically: "true"/"false"/"yes"/"no"bool, "null"null, integer/decimal strings → int/float.

Class-based commands

For anything beyond a one-liner, extend Command:

use InitPHP\Console\{Command, Input, InputArgument, Output};

class GreetCommand extends Command
{
    public $command = 'app:greet';

    public function definition(): string
    {
        return 'Greets a person.';
    }

    public function help(): string
    {
        return 'Prints a friendly greeting to the given name.';
    }

    public function arguments(): array
    {
        return [
            new InputArgument('name', InputArgument::STR, 'World', true, 'Who to greet.'),
        ];
    }

    public function execute(Input $input, Output $output)
    {
        $output->success('Hi ' . $input->getArgument('name'));
    }
}

$console->register(GreetCommand::class);

Declared arguments() are validated before execute() runs: missing required arguments or values that do not match the declared type abort the command with an error.

php console.php app:greet --name=Ada
php console.php app:greet --help        # shows the generated usage + parameters

Output

$output->writeln('Plain line');
$output->writeln('Coloured', [], [Output::COLOR_GREEN, Output::BOLD]);
$output->write('No newline; {token} interpolated', ['token' => 42]);

$output->error('Something failed');
$output->success('All good');
$output->warning('Heads up');
$output->info('FYI');

$output->list(['host' => 'localhost', 'port' => 8080]);

for ($i = 0; $i <= 100; $i += 10) {
    $output->progressBar($i, 100);
    usleep(50_000);
}

Interactive prompts

$name = $output->ask('What is your name?');

use InitPHP\Console\Question;

$question = (new Question())
    ->setQuestion('Continue? (yes/no)')
    ->setOptions(['yes', 'no'])
    ->optional()
    ->setDefault('no');

$answer = $output->question($question);

Typing exit or quit at any prompt terminates the application.

Rendering tables

use InitPHP\Console\Utils\Table;

$table = Table::create()
    ->setHeaderStyle(Table::COLOR_RED, Table::BOLD)
    ->setBorderStyle(Table::COLOR_BLUE)
    ->setCellStyle(Table::COLOR_GREEN);

$table->row(['id' => 1, 'name' => 'Matthew S.', 'email' => 'matthew@example.com', 'status' => true])
      ->row(['id' => 2, 'name' => 'Millie J.',  'email' => 'millie@example.com',  'status' => false]);

echo $table; // or $table->getContent()

Non-string cell values are stringified ([NULL], [TRUE], [FALSE], [ARRAY], [CALLABLE], [RESOURCE], or the class name for objects), columns are auto-sized, and mb_strlen() is used when available so multibyte values align correctly.

Documentation

In-depth, example-driven guides live in docs/:

  1. Getting started
  2. Commands
  3. Input: arguments, options & segments
  4. Typed input arguments
  5. Output & formatting
  6. Interactive questions
  7. Tables
  8. Migrating from initphp/cli-table

Migrating from initphp/cli-table

The standalone initphp/cli-table package has been merged into this one as of 2.1 and is now deprecated.

If your code uses \InitPHP\CLITable\Table, no source changes are required — this package ships a class_alias keeping the old fully-qualified name working. Just switch the dependency:

- "initphp/cli-table": "^1.0",
+ "initphp/console": "^2.1"

(initphp/console declares a Composer replace for initphp/cli-table, so the two will never be installed side by side.) When you next touch the code, prefer the canonical namespace:

// Before
use InitPHP\CLITable\Table;
// After
use InitPHP\Console\Utils\Table;

The alias is a transition aid and may be removed in a future major release. See the migration guide for details.

Testing & quality

composer test     # PHPUnit
composer cs       # PHP_CodeSniffer (PSR-12)
composer stan     # PHPStan (level 6)
composer qa       # all of the above

Contributing

Contributions are welcome. Please run composer qa before opening a pull request. See the organisation contributing guidelines.

Credits

License

Released under the MIT License. Copyright © 2022 InitPHP.

initphp/console 适用场景与选型建议

initphp/console 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 127 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 07 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「cli」 「console」 「command」 「command-line」 「terminal」 「table」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 initphp/console 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 initphp/console 我们能提供哪些服务?
定制开发 / 二次开发

基于 initphp/console 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 127
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 7
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-07-06