PHP Luminova: CLI Command Controller (Routable Commands)
Build routed CLI controllers with command groups, named options, and arguments.
The Base Command class in Luminova allows you to build routable CLI tools with the same structure you use for HTTP controllers. It provides a clear way to define, organize, and execute custom commands within your application.
Luminova\Base\Cli\AbstractController uses Luminova's routing system, allowing you to:
- Define individual commands with the
#[Command]attribute. - Group related commands with the class-level
#[Group]attribute.
This is similar to how HTTP controllers work, but for command-line operations. Commands are executed via your front controller:
php /public/index.php <command>Unlike Base Console, which handles lightweight commands directly using novakit, the Base Command is designed for full routing and tight integration with your application.
This approach makes it easy to add CLI features without additional learning, commands follow familiar controller patterns.
Features
Command MetadataDefine commands with clear usages, options, and descriptions that display with
--help.Input HandlingAutomatically parse arguments, validate input, and execute the right method.
Command GroupingOrganize commands logically using groups to keep your code clean.
Access ControlRestrict commands to specific system users if needed.
CustomizableAdd custom handlers, define new options, or integrate third-party tools.
ReusabilityUse the same controller logic for CLI and HTTP requests, enabling smooth integration.
For formatting command output, use the Luminova Terminal helper.All methods are static and available in the CLI environment for command tasks.
Examples
Help Command
To print help information related to a specific novakit command.
php index.php <command> --helpOptional Help DisplayYou can create a custom help display or rely on the default formatting provided by Luminova.
Command Execution Pattern
Navigate to your project's public directory:
cd path/to/your-project/publicRun your command using this pattern:
php index.php <group-name> <command-name> <arguments>To show help for a command group:
php index.php <group-name> --helpNotes:
- The
group-namecomes first, followed by thecommand-nameand any arguments. - Arguments can appear in any order after the command group.
Default Flags
Use these flags with commands to modify output formatting.
--no-header: Omits the header from the output.php index.php <command> --no-header--no-color: Disables colored output.php index.php <command> --no-color--no-ansi: Disables ANSI formatting for terminals that don't support it.php index.php <command> --no-ansi--no-profiling: Disables showing performance profiling after command execution.php index.php <command> --no-profiling
Building Command-Line Tools
Creating CLI tools in Luminova is straightforward. Its routing system mirrors HTTP routing, so you can apply the same logic you already know to your command-line commands.
Command Controllers
To create a new command controller:
Create Your ControllerPlace your classes in
/app/Controllers/Cli/and make sure they extendLuminova\Base\Cli\AbstractController.Define Your MethodsImplement commands using either PHP Attributes or code-based routing with the Router class.
Routing Command Controllers
Code-Based Routing Example
Define routes in /routes/cli.php:
use Luminova\Routing\Router;
Router::group('blog', static function(Router $router) {
// Command without arguments
Router::command('list', 'BlogCommand::blogs');
// Command with a method argument
Router::command('list/limit/(:int)', 'BlogCommand::blogs2');
});Attribute-Based Routing Example
Use PHP attributes directly in your command class:
namespace App\Controllers\Cli;
use App\Models\Blog;
use Luminova\Command\Terminal;
use Luminova\Attributes\Group;
use Luminova\Attributes\Command;
#[Group(name: 'blog')]
class BlogCommand extends \Luminova\Base\Cli\AbstractController
{
protected string $group = 'blog';
protected string $name = 'blog-command';
public function help(array $helps): int
{
return STATUS_ERROR;
}
#[Command('list')]
public function blogs(int $limit = 10): int
{
$limit = (int) $this->option('limit', 'l', $limit);
Terminal::writeln("Limit: {$limit}");
var_export(Blog::all(limit: $limit));
return STATUS_SUCCESS;
}
#[Command('list/limit/(:int)')]
public function blogs2(int $limit = 10): int
{
Terminal::writeln("Limit: $limit");
var_export(Blog::all(limit: $limit));
return STATUS_SUCCESS;
}
}Note:Both routing methods produce the same results; use whichever style fits your project.
Executing Command
You can specify arguments for your commands in various ways. For example, to list blogs with a limit of 3:
cd path/to/project/public
php index.php blog list --limit=3 # Command with options
php index.php blog list limit=3 # Command with method argumentDisplaying Command Help
To print help for the blog command, use the following command:
php index.php blog --helpCatching Exceptions
In the Luminova framework, exceptions in CLI operations are managed effectively. To enable exception handling, follow these guidelines:
Enable Exception Handling
Environment Configuration:
You can enable exception handling globally by setting the following option in your environment file:
throw.cli.exceptions = trueTemporary Enablement:
If you want to enable exception handling temporarily for the current script execution, you can use the following global function. Call it before your script runs or within the controller's __construct, onCreate, or any executing controller method:
setenv('throw.cli.exceptions', true);Class Definition
- Full namespace:
Luminova\Base\Cli\AbstractController - This class is abstract.
- This class implements Luminova\Interface\RoutableInterface
Properties
allowIncludes
Allows direct PHP include/require statements in this class. When enabled, the debugger skips include/require enforcement for the controller.
protected bool $allowIncludes = false;See the
#[AllowDirectIncludes]class-level attribute for the attribute-based equivalent.
app
Lazy loaded application instance.
protected readonly LazyObjectInterface $app;This allows accessing, command arguments, options, flags or full executed command raw-string via the application instance.
input
Executed command object.
protected readonly Luminova\Command\Input $input;This allows accessing, command arguments, options, flags or full executed command raw-string.
See the Command Input class documentation for details.
group
The group name for the current command controller class. This group is used for router capture authentication to ensure that commands within the same group are executed accordingly (e.g., php index.php <command-group-name> <command> <arguments>).
protected string $group = '';name
The execution command name for the current controller class. This name is used internally to build information about your command, which can be utilized in displaying command help.
protected string $name = '';usages
Command usage instructions. Keys represent the command usage, and values describe the usage. This can be either a string or an associative array of usage examples.
/**
* @var array<string|int, string>|string
*/
protected array|string $usages = '';options
Available command options. Keys represent the options, and values describe them (e.g., ['-f, --foo' => 'Foo description']).
/**
* @var array<string|int, string>
*/
protected array $options = [];Examples Property
Examples demonstrating command usage.
/**
* @var array<string|int, string>
*/
protected array $examples = [];description
A detailed description of your command to help users understand its purpose and functionality.
protected string $description = '';users
Defines a list of allowed system users who can execute the command. If the array is empty, all users are allowed by default.
/**
* @var array<int, string>
*/
protected array $users = [];Example:
Only the following users are permitted to run this command:
/**
* @var array<int, string>
*/
protected array $users = ['www-data', 'ubuntu', 'admin'];Note: This is useful for restricting sensitive commands to specific system-level users.
authentication
The authentication property allows you to configure login protection for CLI commands using either passwords or public/private key authentication.
Supported Array Keys / Database Column Names:
auth(string)– Type of authentication, such aspasswordorkey.content(string)– The hashed password (for password login), public key content, or path to a public key file. Leave empty for public access without a password.updated_at(datetime)– Records the last time authentication was used or updated.
/**
* @var array<string, mixed>|null
*/
protected ?array $authentication = null;Properties
| Name | Type | Description |
|---|---|---|
storage | string | Authentication storage. Examples use database or filesystem. |
tableName | string | Table name when using database storage. |
storagePath | string | Path to the PHP file returning users when using filesystem storage. |
Examples
You can load authentication data from a database or a PHP file:
From Database:
[
'storage' => 'database',
'tableName' => 'foo_cli_users'
]From Filesystem (e.g., auths.php):
[
'storage' => 'filesystem',
'storagePath' => 'writeable/auth/cli_users.php'
]Note:When using the filesystem, your PHP file must return an array of users.
Methods
__construct
Initialize the terminal and the shared application, then call onCreate(). The router assigns command input after construction.
public function __construct()onCreate
Command on create method, an alternative method to __construct().
protected function onCreate(): voidhelp
This allows you to override the default help display implementation.When you implement your custom help information display, you must return STATUS_SUCCESS else return STATUS_ERROR to tell the framework to keep using the default help implementation.
To call help command: php index.php groupName --help
abstract public function help(array $helps): intParameters:
| Parameter | Type | Description |
|---|---|---|
$helps | array<string, mixed> | Receives the helps information about command. |
Return:
int - Return status code success as implemented, error using default implementation.
Help arguments array keys
class- The class name of the command (Note: this key may not be available if you extendBaseConsole).group- The group name of the command.name- The name of the command.description- The description of the command.users- Available command users.authentication- Command authentication information.usages- The usages of the command.options- The available options for the command.examples- The examples of the command.
parse
Parses and processes the command-line arguments and options for the executed command, making them accessible through the input property.
If the input object already exists, its underlying command data is replaced with the new $command array instead of creating a new instance. When the controller defines $options, their keys are registered as known options for validation via Input::hasUnknownOption().
public final function parse(array $command): InputParameters:
| Parameter | Type | Description |
|---|---|---|
$command | array<string, mixed> | Command arguments, options, and flags extracted from CLI execution. |
Return:
Input - Returns instance of input.
Note:This method is invoked internally by the routing system when dispatching a command. You generally won't need to call it directly.
Command Params:
| Key | Type | Description |
|---|---|---|
group | string | Command group. |
name | string | Command name. |
arguments | array<int|string, mixed> | Parsed arguments. |
options | array<string, mixed> | Parsed options. |
command | string | Command line assembled by the parser. |
argv | string[] | Original command-line tokens. |
input | string | Command-line input. |
params | string[] | Command parameters used by routing. |
classMethod | string | Controller method selected by the router. |
getString
Retrieves the full command-line execution string for the current command.
protected function getString(): stringReturn:
string - Return the full command-line string.
Example:
Given a command with: php index.php foo user=1 --no-cache
Outputs:
echo $this->getString();
// index.php index.php foo user=1 --no-cacheoption
Retrieves an option value of executed command based on the specified key or alias. It calls getOption() for a single key and getAnyOption() when you provide an alias.
protected function option(string $key, ?string $alias = null, mixed $default = false): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The primary key for the option. |
$alias | string|null | An optional alias for the option. |
$default | mixed | The default value to return if the option is not found. |
Return:
mixed - Return the value of the option, or the default if not found.
Example:
Given a command with option --verbose or -v.
Outputs:
$verbose = $this->option('verbose', 'v', false);
// Returns true if either option is set.Given a command with option --address=192.160.0.1 or -a=192.160.0.1.
Outputs:
$address = $this->option('address', 'a', null);
// Returns 192.160.0.1 if either option is set.argument
Retrieve a command-line argument by position or by matching a prefix in the argument text.
- If the argument is specified as a string (name), it searches all arguments for a match.
- If the argument is in "key=value" format, the value portion (after
=) is returned. - If an integer index is provided, it retrieves the argument by position.
protected function argument(string|int $index): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$index | string|int | The index (integer) or name (string) of the argument. |
Return:
mixed - Value after = for a matching argument, or the full argument if it has no =. A missing positional argument returns null.
Example:
Given a routed command that accepts two positional arguments:
php index.php foo write example.txt overwrite$file = $this->argument(0); // 'example.txt'
$mode = $this->argument(1); // 'overwrite'The terminal parser treats file=example.txt and mode=write as options. Read those with $this->option('file') and $this->option('mode').
upload
Uploads a file in command line interface to a specified directory.
This method handles uploading a file from either a local path or a base64 encoded string.It creates the target directory if it doesn't exist and generates a unique filename if necessary.
protected function upload(string $file, string $directory, ?string $name = null): string|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$file | string | The path to the file, text content or a base64 encoded string of the file content. |
$directory | string | The target directory where the file should be uploaded. |
$name | string|null | Optional. The desired name for the uploaded file (e.g, file.txt).If null, a name will be generated. |
Return:
string|bool - Returns the path of the uploaded file on success, or false on failure.