PHP Luminova: Base Routable CLI Controller
Base command, Luminova's Framework for command-line operations - controller base class for NovaKit CLI Tool.
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\Command uses Luminova’s routing system, allowing you to:
- Define individual commands with the
#[Route]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\Command.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::blogs');
});Attribute-Based Routing Example
Use PHP attributes directly in your command class:
namespace App\Controllers\Cli;
use Luminova\Base\Command;
use Luminova\Command\Terminal;
use Luminova\Attributes\Route;
use Luminova\Attributes\Group;
#[Group(name: 'blog')]
class BlogCommand extends Command
{
protected string $group = 'blog';
protected string $name = 'blog-command';
public function help(array $helps): int
{
return STATUS_ERROR;
}
#[Route('list', group: 'blog')]
public function blogs(int $limit = 10): int
{
$limit = $this->input->getAnyOption('limit', 'l', 10);
$blog = new Blog();
Terminal::writeln("Limit: {$limit}");
var_export($blog->select($limit));
return STATUS_SUCCESS;
}
#[Route('list/limit/(:int)', group: 'blog')]
public function blogs2(int $limit = 10): int
{
$blog = new Blog();
Terminal::writeln("Limit: $limit");
var_export($blog->select($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
- Class namespace:
Luminova\Base\Command - This class implements: \Luminova\Interface\RoutableInterface
Properties
app
Lazy loaded application instance.
protected readonly Luminova\Foundation\Core\Application<Luminova\Interface\LazyObjectInterface> $app;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 = '';usage
A description of your command usages. This can be either a string or an array of usage examples.
protected array<string,string>|string $usage = [];options
A more expressive way to describe your command options and their descriptive messages. The array key represents the command option, while the value is a description of the option (e.g., ['-f, --foo' => 'Foo description']).
protected array<string,mixed> $options = [];examples
Examples of how to use the command. This allows you to provide full examples demonstrating command usage.
protected array<string,mixed> $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.
protected array<int,string> $users = [];Example:
Only the following users are permitted to run this command:
protected array<int,string> $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.
protected ?array<string, mixed> $authentication = null;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
onCreate
Command on create method, an alternative method to __construct().
protected 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 help(array $helps): int;Parameters:
| Parameter | Type | Description |
|---|---|---|
$helps | array<string,mixed> | Receives the helps information about command. |
Return Value
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.usages- The usages of the command.options- The available options for the command.examples- The examples of the command.
app
Initialize and retrieve the application instance.
protected final app(): \App\ApplicationReturn Value
\App\Application - Return the application instance.
getString
Retrieves the full command-line execution string for the current command.
This method returns the entire command string used to run the current script, including the command name, and any arguments or options passed. Useful for logging or debugging purposes to see the exact command structure.
protected final getString(): stringReturn Value
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. This method is an alias of the parent getAnyOption method.
protected option(string $key, ?string $alias = null, mixed $default = false): mixed Parameters:
| 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 Value
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
Retrieves a command-line argument by its index or name, extending the parent functionality.
This method extends the parent's functionality by allowing arguments to be retrieved based on their name as well as their index. The parent getArgument method only supports retrieval by index, whereas this method adds the ability to retrieve arguments by name.
- 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 argument(string|int $index): mixed Parameters:
| Parameter | Type | Description |
|---|---|---|
$index | string\int | The index (integer) or name (string) of the argument. |
Return Value
mixed - Return the argument value, or the full argument if no '=' is found, or null if not found.
Example:
Given a command with arguments:
php index.php foo file=example.txt mode=writeOutputs:
$file = $this->argument('file'); // Returns 'example.txt'
$mode = $this->argument('mode'); // Returns 'write'Same as above:
$file = $this->argument(1); // Returns 'example.txt'
$mode = $this->argument(2); // Returns 'write'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 upload(string $file, string $directory, ?string $name = null): string|falseParameters:
| 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 Value
string|false - Returns the path of the uploaded file on success, or false on failure.