Interactive questions, menus, and formatted output for PHP console applications.
Use Command to ask questions from your own PHP code, or Prompt to collect a set of answers from an array of steps. Prompts works independently of the MaplePHP framework.
Command · Prompt · Validation · Choices · Progress · ANSI · Reference
Prompts requires PHP 8.2 or later. Install it in your application with Composer.
composer require maplephp/promptsAdd a question wherever your script needs an answer. Save this as setup.php beside your vendor directory and run php setup.php.
<?php
require __DIR__ . '/vendor/autoload.php';
use MaplePHP\Prompts\Command;
$cli = new Command();
$name = $cli->ask('Project name');
$database = $cli->select('Database', [
'sqlite' => 'SQLite',
'mysql' => 'MySQL',
'pgsql' => 'PostgreSQL',
]);
$cli->success("Settings collected for $name ($database).");Use the arrow keys to move and Enter to choose. Selecting MySQL returns 'mysql', the array key, so your code gets a stable value while the menu can use a readable label.
Menus automatically offer numbered choices when arrow-key navigation is unavailable.
Define the questions, defaults, and validation rules in an array, then collect the answers with prompt().
<?php
require __DIR__ . '/vendor/autoload.php';
use MaplePHP\Prompts\Prompt;
$steps = [
'name' => [
'message' => 'Project name',
'default' => 'atlas',
'validate' => ['length' => [3, 40]],
'error' => 'Use between 3 and 40 characters.',
],
'database' => [
'type' => 'select',
'message' => 'Database',
'items' => ['sqlite' => 'SQLite', 'mysql' => 'MySQL'],
],
'approved' => [
'type' => 'confirm',
'message' => 'Create this project?',
],
];
$installer = (new Prompt())->setTitle('New project')->set($steps);
$answers = $installer->prompt();
if ($answers === false) {
exit(1);
}
$installer->getCommand()->success(
"Settings approved for {$answers['name']} ({$answers['database']})."
);Pressing Enter at the project name uses atlas. Choosing SQLite and answering yes to the confirmation produces this result.
['name' => 'atlas', 'database' => 'sqlite', 'approved' => 1]The array keys become the keys in your answers. Invalid input repeats the question with your error message. A declined confirmation, exhausted input, or handled interrupt returns false.
prompt() consumes completed steps. To run the whole installer again, reload them with set($steps).
For definitions you want to run repeatedly or load from storage, use runDefinition().
$installer = new Prompt();
$answers = $installer->runDefinition($steps);Each call starts from the first step. You can also load $steps with json_decode($json, true) from a file or database. Stored definitions support literal text, choices, nested arrays, and supported validation rules. The full definition is checked before any questions are asked.
PHP callbacks belong in workflows built with set(). An items callback on a continue step receives the previous answer and returns follow-up steps, or false to skip them. For example, a MySQL choice can lead to host and password questions while SQLite skips them. Nested answers are grouped under the continue step’s key.
| Type | Answer |
|---|---|
text (default) |
A string. A blank answer uses default when supplied. |
password, mask, invisible |
A hidden string. |
select, search |
The original key of the chosen item. |
multiselect |
The selected keys in definition order. default holds initially selected keys. |
list |
An array of trimmed, comma-separated strings. |
toggle |
1 for yes or 0 for no. |
confirm |
1 for yes. Answering no stops the workflow. |
continue |
Nested answers, or true when a callback skips the step. |
message |
Prints a notice without adding an answer. |
The shorter examples below build on the first script, using its $cli instance and Composer autoloader.
askValidated() keeps asking until an answer passes your rules.
$email = $cli->askValidated(
'Administrator email',
['isEmail' => []],
'Please enter a valid email address.'
);Administrator email: alex
Please enter a valid email address.
Administrator email: alex@example.com
Rules come from MaplePHP Validate. Each name takes an array of arguments, so ['length' => [3, 40]] accepts between 3 and 40 characters. Put several rules in the same map to require them all to pass. Use the same maps under a Prompt step’s validate field.
For application-specific checks, pass a callback that returns true to accept the answer.
$slug = $cli->askValidated(
'Project slug',
static fn (string $value): bool => preg_match('/\A[a-z0-9-]+\z/', $value) === 1,
'Use lowercase letters, numbers, and hyphens.'
);In a Prompt step, put that callback under validator. The older callable validate has the opposite convention, with true requesting a retry. Use one validation field per step.
selectWithSearch() filters a list as the user types.
$timezone = $cli->selectWithSearch('Timezone', [
'Europe/Stockholm' => 'Stockholm',
'Europe/London' => 'London',
'America/New_York' => 'New York',
'America/Los_Angeles' => 'Los Angeles',
]);Type los to find Los Angeles. Pressing Enter returns 'America/Los_Angeles'. Search matches a case-insensitive, literal part of the label. Backspace edits the filter, and the arrows move through the results. A Prompt definition uses 'type' => 'search' with the same items map.
multiSelect() lets the user choose several items.
$features = $cli->multiSelect('Include in this project', [
'api' => 'API endpoints',
'mail' => 'Email notifications',
'reports' => 'Reports',
], defaults: ['api']);Use Space to toggle an item and Enter to accept. The answer contains original keys such as ['api', 'reports']. An empty selection returns [].
Create a bar with the amount of work to do, then call advance() after each item finishes. This example calculates checksums for the library’s PHP source files.
$files = glob(__DIR__ . '/vendor/maplephp/prompts/src/*.php') ?: [];
$checksums = [];
$bar = $cli->progressBar(count($files), width: 24);
try {
foreach ($files as $file) {
$hash = hash_file('sha256', $file);
if ($hash === false) {
throw new RuntimeException("Could not read $file.");
}
$checksums[$file] = $hash;
$bar->advance();
}
} finally {
$bar->finish();
}A terminal updates one line. For three files, the final line is the following.
[========================] 3/3
Reaching the total finishes automatically. finish() also closes a partial bar at its actual count, such as 1/3 if work stopped after the first file. Redirected output gets one plain count line. You can advance by a batch with advance(10).
Style a heading, highlight a choice, or give your questions a look that fits your tool. ANSI helpers return strings, so you can use them with questions and output alike.
$ansi = $cli->getAnsi();
$cli->line($ansi->blueBg(' ATLAS '));
$cli->line($ansi->dim('Choose a name for your project.'));
$name = $cli->ask($ansi->cyan('Project ' . $ansi->bold('name') . ' to create'));The question is cyan, with name in bold. The cyan style resumes after the bold word. You can also apply several styles at once with $ansi->style(['bold', 'cyan'], $text).
| Style | Methods |
|---|---|
| Text | bold(), dim(), italic(), underline(), reverse(), strikethrough() |
| Colors | black(), red(), green(), yellow(), blue(), magenta(), cyan(), white(), grey() |
| Bright colors | brightBlack(), brightRed(), through to brightWhite(). |
| Backgrounds | redBg(), blueBg(), and the corresponding variant for each base color, including bright variants. |
disableAnsi(true) turns off generated styles. Text stays readable, and background labels use brackets. The example above becomes the following.
[ ATLAS ]
Choose a name for your project.
Project name to create: atlas
Passing false restores automatic detection. Style detection uses TERM and the OS. For cursor movement in a custom renderer, check $cli->hasCursorOutput() first.
Blocks writes aligned tables and help sections through your command.
use MaplePHP\Prompts\Themes\Blocks;
$blocks = new Blocks($cli);
$blocks->table(['Setting', 'Value'], [
['Project', 'atlas'],
['Database', 'SQLite'],
]);Setting Value
Project atlas
Database SQLite
Colors and multibyte text are accounted for when aligning columns. addSection() groups help text, addOption() describes a flag, and addExample() adds a usage example. Chain addOption() and addExample() inside a section callback and return the resulting builder. addCode($php) prints a PHP snippet with syntax highlighting.
For a custom menu, use Navigation::navigate($message, $items, $renderer). The renderer receives the focused index and ordered labels. Print one short line per choice so the menu can redraw in place. After selection, getValue() returns the original key and getItem() returns its label.
Arrow-key menus use Unix terminal controls. Windows, piped input, and redirected output use numbered choices. Search reads a filter line followed by a choice number. Multi-select accepts comma-separated numbers, a blank line for defaults, or none to clear the selection.
Command reads stdin and writes stdout by default. To send questions to stderr while leaving stdout for your application’s data, configure its output stream.
use MaplePHP\Http\Stream;
$cli = new Command(stream: new Stream(STDERR));The constructor also accepts a separate PSR-7 stream as input, so tests can supply answers and capture output. Pass your command to new Prompt($cli) to use those streams throughout a workflow.
ask() preserves surrounding whitespace and returns '' for a blank line. mask() reads hidden input, using Unix terminal controls or PowerShell on a native Windows console.
Direct questions throw InputExhaustedException at the end of input. Raw menus and masked reads report a handled interrupt as InputInterruptedException. Both extend MaplePHP\Prompts\Exceptions\PromptException. Catch that exception at your script’s entry point to choose your message and exit status. Workflows return false for either outcome.
| Method | Result or purpose |
|---|---|
ask($message), readline($message) |
Read a string, preserving whitespace. |
askValidated($message, $validator, $error = 'Please try again.') |
Retry until a rule map or callback accepts the answer. |
mask($message) |
Read hidden input. |
list($message) |
Return trimmed, comma-separated strings. |
select($message, $items) |
Return one original choice key. |
selectWithSearch($message, $items) |
Search labels and return one original key. Labels must be nonempty printable single-line UTF-8 strings. |
multiSelect($message, $items, $defaults = []) |
Return unique selected keys in definition order. |
inputSelect($message, $choices) |
Always use numbered input. |
toggle($message), inputToggle($message) |
Return 1 or 0. inputToggle() always reads yes or no. |
confirm($message) |
Read yes or no and return a boolean. |
line($message = '', $break = true) |
Print text or a blank line. Pass false to omit the newline. |
title(), status(), success(), warning(), error() |
Print a heading, status, success, warning, or error. error() returns false; the others return void. |
progressBar($total, $width = 40) |
Create a bar controlled by advance() and finish(). |
progress($expectedRows, $maxLength = 100, $sleep = null) |
Play a fixed-length progress animation. |
withStream($stream) |
Return a copy with different output and the same input. |
getStream(), getInput(), getAnsi() |
Access output, input, and styling. |
hasTerminalInput(), hasCursorOutput(), supportsNavigation() |
Check terminal capabilities. |
getStty() |
Access low-level Unix terminal controls. |
Existing message(), approve(), and statusMsg() calls remain available. message($text) prints and returns false; message($text, true) asks a question. approve() and statusMsg() return false; their newer counterparts are success() and status().
From a checkout with dependencies installed, run php examples/command.php for a report export, or php examples/example.php for an installer with hidden input, validation, and nested questions.
Apache License 2.0.