百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
P

php-cli

> 开发工具
开源

PHP 控制台应用程序变得简单 - 轻松构建出色的控制台应用程序。支持零依赖和自动完成。将其视为极其灵活的工具。

352 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

PHP 控制台应用程序变得简单 - 轻松构建出色的控制台应用程序。支持零依赖和自动完成。将其视为极其灵活的工具。

adhocore/cli

Framework agnostic Command Line Interface utilities and helpers for PHP. Build Console App with ease, fun and love.

  • Command line application made easy
  • Inspired by nodejs commander (thanks tj)
  • Zero dependency.
  • For PHP7, PHP8 and for good

What's included

Core: Argv parser · Cli application · Shell

IO: Colorizer · Cursor manipulator · Progress bar · Stream writer · Stream reader

Other: Autocompletion

Installation

bash
# PHP8.0 and above v1.0.0
composer require adhocore/cli:^v1.0.0

# PHP 7.x
composer require adhocore/cli:^v0.9.0

Usage

Argv parser

…

Command help

It can be triggered manually with $command->showHelp() or automatic when -h or --help option is passed to $command->parse().

For above example, the output would be:

Command version

It can be triggered manually with $command->showVersion() or automatic when -V or --version option is passed to $command->parse().

For above example, the output would be:

0.0.1-dev

Console app

Definitely check adhocore/phint - a real world console application made using adhocore/cli.

Here we simulate a git app with limited functionality of add, and checkout. You will see how intuitive, fluent and cheese building a console app is!

Git app

…

Organized app

Instead of inline commands/actions, we define and add our own commands (having interact() and execute()) to the app:

…

Grouping commands

Grouped commands are listed together in commands list. Explicit grouping a command is optional. By default if a command name has a colon : then the part before it is taken as a group, else * is taken as a group.

Example: command name app:env has a default group app, command name appenv has group *.

php
// Add grouped commands:
$app->group('Configuration', function ($app) {
    $app->add(new ConfigSetCommand);
    $app->add(new ConfigListCommand);
});

// Alternatively, set group one by one in each commands:
$app->add((new ConfigSetCommand)->inGroup('Config'));
$app->add((new ConfigListCommand)->inGroup('Config'));
...

Default command

By default, running your CLI app without any arguments will show the help screen. However you can set the default action to run one of your commands either by setting the third parameter of the add function to true or by using the defaultCommand function.

php
$app->add(new InitCommand, 'i', true);

// Alternatively
$app->command('init', 'Init something', 'i');
$app->defaultCommand('init');

// Retrieve the name of the default command
$default_command = $app->getDefaultCommand();

Exception handler

Set a custom exception handler as callback. The callback receives exception & exit code. The callback may rethrow exception or may exit the program or just log exception and do nothing else.

php
$app = new Ahc\Cli\Application('App', 'v0.0.1');
$app->add(...);
$app->onException(function (Throwable $e, int $exitCode) {
    // send to sentry
    // write to logs

    // optionally, exit with exit code:
    exit($exitCode);

    // or optionally rethrow, a rethrown exception is propagated to top layer caller.
    throw $e;
})->handle($argv);

App help

It can be triggered manually with $app->showHelp() or automatic when -h or --help option is passed to $app->parse(). Note If you pass something like ['app', cmd', '-h'] to $app->parse() it will automatically and instantly show you help of that cmd and not the $app.

For above example, the output would be:

App version

Same version number is passed to all attached Commands. So you can trigger version on any of the commands.

Shell

Very thin shell wrapper that provides convenience methods around proc_open().

Basic usage

php
$shell = new Ahc\Cli\Helper\Shell($command = 'php -v', $rawInput = null);

// Waits until proc finishes
$shell->execute($async = false); // default false

echo $shell->getOutput(); // PHP version string (often with zend/opcache info)

Advanced usage

php
$shell = new Ahc\Cli\Helper\Shell('php /some/long/running/scipt.php');

// With async flag, doesnt wait for proc to finish!
$shell->setOptions($workDir = '/home', $envVars = [])
    ->execute($async = true)
    ->isRunning(); // true

// Force stop anytime (please check php.net/proc_close)
$shell->stop(); // also closes pipes

// Force kill anytime (please check php.net/proc_terminate)
$shell->kill();

Timeout

php
$shell = new Ahc\Cli\Helper\Shell('php /some/long/running/scipt.php');

// Wait for at most 10.5 seconds for proc to finish!
// If it doesnt complete by then, throws exception
$shell->setOptions($workDir, $envVars, $timeout = 10.5)->execute();

// And if it completes within timeout, you can access the stdout/stderr
echo $shell->getOutput();
echo $shell->getErrorOutput();

Cli Interaction

You can perform user interaction like printing colored output, reading user input programatically and moving the cursors around with provided Ahc\Cli\IO\Interactor.

php
$interactor = new Ahc\Cli\IO\Interactor;

// For mocking io:
$interactor = new Ahc\Cli\IO\Interactor($inputPath, $outputPath);

Confirm

php
$confirm = $interactor->confirm('Are you happy?', 'n'); // Default: n (no)
$confirm // is a boolean
    ? $interactor->greenBold('You are happy :)', true)  // Output green bold text
    : $interactor->redBold('You are sad :(', true);     // Output red bold text

Single choice

php
$fruits = ['a' => 'apple', 'b' => 'banana'];
$choice = $interactor->choice('Select a fruit', $fruits, 'b');
$interactor->greenBold("You selected: {$fruits[$choice]}", true);

Multiple choices

php
$fruits  = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$choices = $interactor->choices('Select fruit(s)', $fruits, ['b', 'c']);
$choices = \array_map(function ($c) use ($fruits) { return $fruits[$c]; }, $choices);
$interactor->greenBold('You selected: ' . implode(', ', $choices), true);

Prompt free input

php
$any = $interactor->prompt('Anything', rand(1, 100)); // Random default
$interactor->greenBold("Anything is: $any", true);

Prompt with validation

php
$nameValidator = function ($value) {
    if (\strlen($value) prompt('Name', null, $nameValidator, 5);
$interactor->greenBold("The name is: $name", true);

Prompt hidden

On windows platform, it may change the fontface which can be fixed.

php
$passValidator = function ($pass) {
    if (\strlen($pass) promptHidden('Password', $passValidator, 2);

IO Components

The interactor is composed of Ahc\Cli\Input\Reader and Ahc\Cli\Output\Writer while the Writer itself is composed of Ahc\Cli\Output\Color. All these components can be used standalone.

Color

Color looks cool!

php
$color = new Ahc\Cli\Output\Color;

Simple usage

php
echo $color->warn('This is warning');
echo $color->info('This is info');
echo $color->error('This is error');
echo $color->comment('This is comment');
echo $color->ok('This is ok msg');

Custom style

php
Ahc\Cli\Output\Color::style('mystyle', [
    'bg' => Ahc\Cli\Output\Color::CYAN,
    'fg' => Ahc\Cli\Output\Color::fg256(57), // 256 colors can be used as well
    'bold' => 1, // You can experiment with 0, 1, 2, 3 ... as well
]);

echo $color->mystyle('My text');

Built-in styles

There are a number of pre-defined built-in styles that allows you granular customization to different output conditions such as help and prompts:

  • answer
  • choice
  • comment
  • error
  • help_category
  • help_description_even
  • help_description_odd
  • help_example
  • help_footer
  • help_group
  • help_header
  • help_item_even
  • help_item_odd
  • help_summary
  • help_text
  • info
  • logo
  • ok
  • question
  • version
  • warn

Overriding a built-in style works the same way as defining a new style:

php
Ahc\Cli\Output\Color::style('error', [
    'fg' => Ahc\Cli\Output\Color::RED,
    'bold' => 1,
]);

Disable colors

php
Ahc\Cli\Output\Color::$enabled = false;

Colors will be automatically disabled if the NO_COLOR environment variable is set to true.

Cursor

Move cursor around, erase line up or down, clear screen.

php
$cursor = new Ahc\Cli\Output\Cursor;

echo  $cursor->up(1)
    . $cursor->down(2)
    . $cursor->right(3)
    . $cursor->left(4)
    . $cursor->next(0)
    . $cursor->prev(2);
    . $cursor->eraseLine()
    . $cursor->clear()
    . $cursor->clearUp()
    . $cursor->clearDown()
    . $cursor->moveTo(5, 8); // x, y

Progress Bar

Easily add a progress bar to your output:

php
$progress = new Ahc\Cli\Output\ProgressBar(100);
for ($i = 0; $i current($i);

    // Simulate something happening
    usleep(80000);
}

You can also manually advance the bar:

php
$progress = new Ahc\Cli\Output\ProgressBar(100);

// Do something

$progress->advance(); // Adds 1 to the current progress

// Do something

$progress->advance(10); // Adds 10 to the current progress

// Do something

$progress->advance(5, 'Still going.'); // Adds 5, displays a label

You can override the progress bar options to customize it to your liking:

…

Writer

Write anything in style.

php
$writer = new Ahc\Cli\Output\Writer;

// All writes are forwarded to STDOUT
// But if you specify error, then to STDERR
$writer->errorBold('This is error');

Output formatting

You can call methods composed of any combinations: '', 'bold', 'bg', 'fg', 'warn', 'info', 'error', 'ok', 'comment' ... in any order (eg: bgRedFgBlaock, boldRed, greenBold, commentBgPurple and so on ...)

php
$writer->bold->green->write('It is bold green');
$writer->boldGreen('It is bold green'); // Same as above
$writer->comment('This is grayish comment', true); // True indicates append EOL character.
$writer->bgPurpleBold('This is white on purple background');

Free style

Many colors with one single call: wrap text with tags and For NL/EOL just use or or ``.

Great for writing long colorful texts for example command usage info.

php
$writer->colors('This is redThis has bg Green');

Raw output

php
$writer->raw('Enter name: ');

Tables

Just pass array of assoc arrays. The keys of first array will be taken as heading. Heading is auto inflected to human readable capitalized words (ucwords).

php
$writer->table([
    ['a' => 'apple', 'b-c' => 'ball', 'c_d' => 'cat'],
    ['a' => 'applet', 'b-c' => 'bee', 'c_d' => 'cute'],
]);

Gives something like:

+--------+------+------+
| A      | B C  | C D  |
+--------+------+------+
| apple  | ball | cat  |
| applet | bee  | cute |
+--------+------+------+

Designing table look and feel

Just pass 2nd param $styles:

…

You can define the style of a cell dynamically using a callback. You could then apply one style or another depending on a value.

php
$rows = [
    ['name' => 'John Doe', 'age' => '30'],
    ['name' => 'Jane Smith', 'age' => '25'],
    ['name' => 'Bob Johnson', 'age' => '40'],
];

$styles = [
    '*:2' => function ($val, $row) {
        return $row['age'] >= 30 ? 'boldRed' : '';
    },
];

$writer->table($rows, $styles);

The example above only processes the cells in the second column of the table. If you want to process any cell, you can use the *:* key. You could then customise each cell in the table

…

Note: Priority in increasing order:

  • odd or even
  • 2:* (row)
  • *:2 or b-c column name (col)
  • *:* any cell in table
  • 1:1 (cell) = highest priority

Justify content (Display setting)

If you want

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPadhocoreargvargv-parsercli-app

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类开发工具
定价开源

> 相关工具

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具