PHP Luminova: CLI Keyboard Input Event
Handle keyboard input in PHP CLI apps. Capture single keys, listen for shortcuts, handle Ctrl+C safely, and build interactive command-line tools with ease using Luminova Keyboard utilities.
The Keyboard utility provides a simple and reliable way to capture and listen for keyboard input in CLI applications. It supports single key capture, conditional waiting, and continuous event listening, with built-in handling for common keys, function keys, arrow keys, and dynamic key combinations like ctrl+, alt+, and ctrl+alt+.
It's designed for interactive command-line tools where precise user input handling matters.
Keyboard Input Examples (CLI)
These examples show how to read keyboard input in a terminal, react to it, and stop when needed.Useful for menus, confirmations, games, installers, and interactive tools.
Capture a Single Key Press
- Detects one key press only
- Useful for confirmations, shortcuts, or quick actions
use Luminova\Command\Keyboard;
$result = Keyboard::capture();
print_r($result);
// Example output:
// [
// 'code' => ' ',
// 'name' => 'ctrl+alt+delete'
// ]code: the raw key code returned by the terminalname: a human-readable key name
React to Specific Keys
A clean and readable way to map key presses to actions.
use Luminova\Command\Keyboard;
$key = Keyboard::capture();
$result = match ($key['name']) {
Keyboard::ENTER => 'Enter key pressed',
Keyboard::LEFT => 'Left arrow pressed',
Keyboard::F12 => 'F12 pressed',
default => 'Unknown key'
};
echo $result;Condition-Based Waiting
This example waits until Ctrl + C is pressed before stopping.
- Pauses execution until a keyboard condition is met based on return value of
$conditioncallback. - Stops execution safely
- Handles
Ctrl + Cinstead of abruptly terminating the script
use Luminova\Command\Keyboard;
use Luminova\Command\Terminal;
Keyboard::readUntil(
fn (string $code, ?string $name): bool => $name === Keyboard::CTRL_C,
fn (string $code, ?string $name): void => Terminal::print("Interrupted\n")
);Condition-Based Wait With Return Value
Allows you to return a value and terminate execution when the condition is met.
- Enables graceful shutdown
- Ideal for long-running commands or processes
use Luminova\Command\Keyboard;
use Luminova\Command\Terminal;
$result = Keyboard::readUntil(
fn (string $code, ?string $name): bool => $name === Keyboard::CTRL_C,
function (string $code, ?string $name): string {
Terminal::print("Interrupted\n");
return 'Process stopped by user';
}
);
echo $result;Listen Continuously for Keyboard Events
Listens continuously and executes the callback only when the pressed key matches one of the defined listeners.Listening stops when the callback returns true or when the timeout expires.
use Luminova\Command\Keyboard;
use Luminova\Command\Terminal;
Keyboard::listen(
function (string $code, ?string $name): bool {
Terminal::writeln("Pressed: {$name}");
// Return true to stop listening
return $name === Keyboard::ESCAPE;
},
listeners: [
Keyboard::UP,
Keyboard::DOWN,
Keyboard::LEFT,
Keyboard::RIGHT,
Keyboard::ESCAPE
],
10000 // optional timeout in milliseconds (10 seconds)
);Class Definition
- Full namespace:
\Luminova\Command\Keyboard - This class is marked as final and can't be subclassed
Constants
Supported keyboard key events that can be detected and handled by the CLI keyboard listener.
| Constant | Value | Description |
|---|---|---|
UP | 'up' | Arrow key used to move up in menus or lists. |
DOWN | 'down' | Arrow key used to move down in menus or lists. |
LEFT | 'left' | Arrow key used to move left or go back. |
RIGHT | 'right' | Arrow key used to move right or go forward. |
HOME | 'home' | Moves the cursor to the beginning of a line or content. |
END | 'end' | Moves the cursor to the end of a line or content. |
INSERT | 'insert' | Toggles insert or overwrite mode (if supported by terminal). |
DELETE | 'delete' | Deletes the character after the cursor. |
PAGE_UP | 'page_up' | Scrolls up one page or screen. |
PAGE_DOWN | 'page_down' | Scrolls down one page or screen. |
F1 | 'f1' | Function key, often used for help. |
F2 | 'f2' | Function key, commonly used for rename or edit actions. |
F3 | 'f3' | Function key, behavior depends on application. |
F4 | 'f4' | Function key, behavior depends on application. |
F5 | 'f5' | Function key, often used for refresh or reload. |
F6 | 'f6' | Function key, behavior depends on application. |
F7 | 'f7' | Function key, behavior depends on application. |
F8 | 'f8' | Function key, behavior depends on application. |
F9 | 'f9' | Function key, behavior depends on application. |
F10 | 'f10' | Function key, often used to activate menus. |
F11 | 'f11' | Function key, commonly used to toggle fullscreen. |
F12 | 'f12' | Function key, often used for advanced or debug actions. |
BACKSPACE | 'backspace' | Deletes the character before the cursor. |
TAB | 'tab' | Moves focus forward or indents input. |
SHIFT_TAB | 'shift+tab' | Moves focus backward. |
ENTER | 'enter' | Confirms an action or submits input. |
ESCAPE | 'escape' | Cancels the current action or exits a mode. |
CTRL_A | 'ctrl+a' | Selects all content or moves to line start (terminal-dependent). |
CTRL_C | 'ctrl+c' | Interrupts execution or stops the current process. |
CTRL_V | 'ctrl+v' | Pastes clipboard content (terminal-dependent). |
CAPSLOCK | 'capslock' | Toggles uppercase letter mode. |
Note:
In addition to the predefined constants above, the keyboard listener also supports dynamic key combinations.Any key name that matches with the following prefixes will be detected automatically:
ctrl+— for Control key combinations (for example:ctrl+x,ctrl+s)ctrl+alt+— for Control + Alt combinations (for example:ctrl+alt+delete)alt+— for Alt key combinations (for example:alt+f,alt+tab)
Methods
keys
Return all key names currently supported by the Keyboard class.
This includes all mapped keys from KEY_MAP plus heuristic keys like CAPSLOCK.Also includes dynamic keys ctrl+{letter}, ctrl+alt+{letter}, alt+{letter}.
public static keys(): string[]Return Value:
string[] - Returns list of all supported keyboard key names.
isSupported
Check whether a given key name is supported by the Keyboard class.
Also support dynamic keys ctrl+{letter}, ctrl+alt+{letter}, alt+{letter}
public static isSupported(string $name): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The name of the key to check (e.g, Keyboard::ESCAPE). |
Return Value:
bool - Returns true if the key is supported, false otherwise.
capture
Capture a single key press from the terminal.
Reads raw keyboard input and maps common control keys to human-readable names.Designed for interactive CLI usage (menus, navigation, confirmations).
If a timeout is provided, waits up to $timeout milliseconds for a key.If no key is pressed during that time, returns null.
public static capture(?int $timeout = null, ?callable $callback = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$timeout | int|null | Optional wait timeout in milliseconds (default: null). |
$callback | callable|null | Optional callback invoked with the raw ANSI key sequence and its mapped name. |
Return Value:
array{code: string, name: ?string}|mixed - Returns key event or the callback result.
Note:Terminals do not emit a real Caps Lock key event.Caps Lock is detected when an uppercase letter is received.
listen
Listen for key events and fire a callback when a matching key is detected.
Continuously reads keyboard input and triggers the given callback for each key eventthat matches the provided filter. The listener can optionally stop after a timeoutor when the callback returns true.
public static listen(callable $callback, string[] $listeners, ?int $timeout = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | callable | Callback invoked for each matching key press. Must return a boolean: - true to stop listening,- false to continue listening. |
$listeners | string[] | List of key names to listen for. Only these keys trigger the callback. |
$timeout | int|null | Optional timeout in milliseconds (default: null wait indefinitely). |
Throws:
- \Luminova\Exceptions\RuntimeException - If the callback returns a non-boolean value.
readUntil
Read keys repeatedly until a specific condition is satisfied.
Continuously reads individual key presses from the keyboard and evaluateseach one against the provided condition callback. When the condition returnstrue, reading stops and the corresponding key event is returned (or passedto an optional result callback).
This method is useful for interactive CLI scenarios, such as waiting forEnter, Esc, Ctrl+C, or any custom key sequence.
public static readUntil(callable $condition, ?callable $callback = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$condition | callable | Callback that receives the raw key code and mapped name. Return true to stop reading. |
$callback | callable|null | Optional callback invoked with the key event when the condition is met. |
Return Value:
array{code: string, name: ?string}|mixed - Returns the key event or the result of the callback when the condition is satisfied.
Throws:
- \Luminova\Exceptions\RuntimeException - If $condition returns a non-boolean value.
Example:
Wait for Enter:
Keyboard::readUntil(fn($k, $n) => $n === Keyboard::ENTER);Note:The
$conditioncallback must return a boolean.Return true to stop reading or false to keep reading.