PHP Luminova: CLI Command Routing
Learn how Luminova CLI commands are defined, grouped, routed, protected with middleware, and handled by CLI controllers using method-based or attribute-based routing.
The CLI Routing system defines and organizes commands for CLI controller classes that extend Luminova Command Controller.
It provides a structured way to:
- Define commands using route-style command definitions.
- Group related commands for better organization.
- Protect commands by applying authentication middleware through guards.
To define CLI commands:
- Use
group()to organize related commands.- Use
command()to register individual commands.- Use
guard()to apply authentication middleware to commands.To get started, see the Luminova Routing System Introduction for an overview of the routing system, configuration, and features shared between HTTP and CLI routing.
Controller Method Handlers
When mapping CLI commands to handlers, you can use either a Closure or a string reference pointing to a controller method. This works the same way as HTTP routing.
The routing system supports controller handlers using either:
- Static-style:
Controller::method - Notation-style:
Controller@method
You don't need to write the full namespace, just the controller's base name and method. The routing system resolves the correct namespace automatically from the registered controller list.
Note:Method based command definitions are strictly defined in
routes/cli.php.
CLI Controller Classes
CLI controllers define properties and the methods that handle CLI commands. Commands are resolved using the controller's group name and, when using attribute routing, the command pattern defined by the #[Command] attribute.
A CLI controller can define its group using the $group property or the #[Group] attribute.
Example:
// /app/Controllers/Cli/Controller.php
namespace App\Controllers\Cli;
use App\Utils\SomeClass;
use Luminova\Base\Command;
use Luminova\Command\Terminal;
use Luminova\Attributes\Command;
use Luminova\Attributes\Group;
#[Group(name: 'demo')]
class Controller extends Command
{
/**
* CLI group name for this controller.
*/
protected string $group = 'demo';
/**
* Display the help message.
*
* @param array $helps Available help information.
*
* @return int STATUS_ERROR
*/
public function help(array $helps): int
{
return STATUS_ERROR; // Use the default help style.
}
#[Command('hello')]
public function hello(SomeClass $object): int
{
$name = $this->option('name', default: 'World');
Terminal::write("Hello, {$name}!");
return STATUS_SUCCESS;
}
}In this example:
demois the CLI command group.#[Command('hello')]maps thehellocommand tohello().SomeClassis automatically resolved and injected when dependency injection is enabled.- Returning
STATUS_SUCCESSindicates successful command execution. - Returning
STATUS_ERRORfromhelp()allows the default help output to be used.
Method-Based Command Routing
Method-based CLI routes are defined in /routes/cli.php.
Commands are organized into groups using the group() method. The group name becomes the base command, while individual commands are registered inside the group using command().
Within /routes/cli.php, Luminova\Routing\Router $router and App\Application $app are automatically available. You only need use statements when explicitly referencing these classes, such as when using them as typed parameters in a closure.
Example:
// /routes/cli.php
use Luminova\Routing\Router;
Router::group('demo', static function (): void {
Router::command('hello', 'Controller::hello');
});The command is executed using the group name followed by the command name:
php index.php demo hello --name="Peter"The resulting command structure is:
demo helloMultiple Commands in a Group
A group can contain multiple commands:
// /routes/cli.php
use Luminova\Routing\Router;
Router::group('blog', static function (): void {
Router::command('all', 'Controller::all');
Router::command('id/(:int)', 'Controller::get');
});The commands can then be executed as follows.
List all blogs:
php index.php blog allShow a blog by ID:
php index.php blog id=2In this example, blog is the group name and id=2 matches the id/(:int) command pattern.
Note:
Method-based CLI routing does not require route attributes. If attributes such as
#[Group]or#[Command]are defined on the controller, they are ignored when the controller is registered through method-based routing.
Middleware
Middleware must return STATUS_SUCCESS when the request or command passes the middleware check, or STATUS_ERROR when it fails.
A truthy return value is also treated as a successful result, unless the request or command has been terminated by another mechanism.
Method-based CLI Middleware
CLI middleware can be applied to commands using the guard() method. Guards can be used to perform command authentication, authorization, validation, or other checks before a command is executed.
To apply a guard to all CLI commands, use the global group name.
Example:
// /routes/cli.php
use Luminova\Routing\Router;
Router::group('blog', function (): void {
Router::guard('blog', 'Controller::middleware');
Router::command('list', 'Controller::list');
});In this example, the guard is associated with the blog command group and is applied when commands in that group are executed.
To apply a guard globally:
Router::guard('global', 'Controller::middleware');The global guard is applied to every CLI command.
When using attribute-based command routing, middleware can be configured through the
middlewareargument of theCommandattribute.
Attribute CLI Middleware
When using attribute-based command routing, CLI middleware can be configured through the middleware argument of the Command attribute.
The middleware can be applied to a specific command or globally using Command::GLOBAL_MIDDLEWARE.
Example:
namespace App\Controllers\Cli;
use Luminova\Attributes\Command;
use Luminova\Attributes\Group;
#[Group('blog')]
class FooCommand extends \Luminova\Base\Command
{
#[Command(middleware: Command::GLOBAL_MIDDLEWARE)]
public function middleware(): int
{
// CLI middleware implementation.
return STATUS_SUCCESS;
}
}In this example, Command::GLOBAL_MIDDLEWARE marks the middleware() method as global CLI middleware, allowing it to run for all CLI commands.
For command-specific middleware, omit
Command::GLOBAL_MIDDLEWAREand define the middleware on the command that requires it.
Dependency Injection
Luminova CLI routing supports automatic dependency injection. You can type-hint dependencies in controller methods or route closures, and Luminova automatically resolves and injects them when the command is executed.
Using a Controller Method:
// /app/Controllers/Cli/Controller.php
namespace App\Controllers\Cli;
use App\Utils\ImageColor;
use Luminova\Command\Terminal;
use Luminova\Attributes\Group;
use Luminova\Attributes\Command;
use Luminova\Command\Utils\Image;
#[Group(name: 'demo')]
class Controller extends Luminova\Base\Command
{
#[Command('draw/image/(:?string)')]
public function drawImageArt(
?string $image,
ImageColor $color
): int
{
$art = Image::draw(
$image ?? '/path/to/image.jpg',
ascii: Image::ASCII_CLASSIC,
width: 50,
height: 50,
grayScale: true,
colors: $color->getArrayColors(),
lazyPrint: [
'pixel' => 50000,
'pixels' => 200000,
]
);
Terminal::write($art);
return STATUS_SUCCESS;
}
}Execute the command:
To draw an image using ASCII:
php index.php demo draw image="/path/to/image.jpg"The $image parameter is populated from the command route, while the ImageColor dependency is automatically resolved and injected by Luminova.
This allows controller methods to declare the dependencies they need without manually creating or resolving their instances.
Attributes
When env(feature.route.attributes) is enabled, CLI routes can be defined using PHP attributes. This keeps command definitions close to their controller methods instead of defining them separately through traditional method-based routing.
Group
A class-scope attribute that assigns a command group name to a CLI controller.
Each controller class can have only one Group attribute.
See Group Attribute for more information.
Command
A method-scope, repeatable attribute used to register a CLI command on a controller method.
See Command Attribute for more information.
Class Definition
- Class namespace:
Luminova\Routing\Router - This class implements: \Luminova\Interface\RouterInterface
- This class is marked as final and can't be subclassed
Methods
group
Organizes CLI commands into a specific group for execution.
Similar to the HTTP bind method, the group method simplifies the organization of CLI commands by grouping related commands under a common name. This is especially useful for commands related to the same controller, making it easier to execute and maintain them. Any non-builtin typed parameter declared on the closure is automatically resolved and injected.
public static group(string $group, Closure $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$group | string | The name of the command group (e.g., blog, user). |
$callback | Closure | A callback function that defines the commands for the group. |
Example:
Grouping CLI commands under a blog group:
Router::group('blog', static function () {
Router::command('list', 'BlogController::blogs'); // Command to list all blogs
Router::command('id/(:int)', 'BlogController::blog'); // Command to fetch a blog by ID
});Executing Commands:
# Navigate to the project's public directory
cd path/to/project/public/
# Execute commands within the `blog` group
php index.php blog list # Lists all blogs
php index.php blog id=4 # Fetches the blog with ID 4Note: Ensure that the group name matches the value of the
$groupproperty defined in the command controller class to avoid routing mismatches or execution errors.
command
Registers a CLI command and its corresponding callback or controller method.
This method is used to define CLI commands, specifying the command name and the callback function or controller method to execute when the command is run in the terminal. Unlike HTTP routes, CLI commands are defined using this method specifically within a group() closure, and do not support arbitrary regular expressions directly — patterns are normalized through the same placeholder syntax used by HTTP routes.
public static command(string $command, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$command | string | The command name or pattern, optionally containing placeholders (e.g., foo, foo/(:int)/bar/(:string)). |
$callback | Closure|string | The callback function or controller method to execute (e.g., ClassBaseName::methodName). |
Example Usage:
Suppose you have a command group blog and a blog command controller class with two methods: list and get. The list method accepts an int argument to determine the number of blogs to list, while the get method accepts a string as the blog ID. You can register these commands with filters like /list/limit/(:int) for the list method and /get/id/(:string) for the get method.
List Command With Method-Based:
// /routes/cli.php
Router::group('blog', function(){
Router::command('/list/limit/(:int)', 'Controller::list');
});List Command With Attribute:
// /App/Controllers/Cli/Controller.php
#[Command('list/limit/(:int)', group: 'blog')]
public function list(int $limit = 10): int
{
return STATUS_SUCCESS;
}Get Command:
// /routes/cli.php
Router::group('blog', function(){
Router::command('/get/id/(:string)', 'Controller::get');
});Get Command With Attribute:
// /App/Controllers/Cli/Controller.php
#[Command('get/id/(:string)', group: 'blog')]
public function get(string $id): int
{
return STATUS_SUCCESS;
}Note:
For commands that don't expect any arguments, you don't need to add any filters — just pass the name, like
foo.Additionally, execution of the command controller must follow this pattern:
php index.php <command-group> <command> <argument>.
guard
Registers a CLI before middleware guard to authenticate commands within a specific group.
The guard method provides middleware security for the CLI implementation. It applies middleware logic to CLI commands within a specified group. The middleware is executed before any command in the group. If the callback returns STATUS_SUCCESS, the routing process continues to execute the matched command. If the callback returns STATUS_ERROR, the routing process terminates, preventing further commands from executing.
Unlike the middleware method, which handles only HTTP method authentication and accepts regular expression patterns, the guard method accepts only the command group name, or global for a middleware that applies to all commands.
public static guard(string $group, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$group | string|'global' | The command group name, or global for middleware that applies to all commands. |
$callback | Closure|string | The callback function or controller method to execute (e.g., ControllerClass::methodName). |
Throws:
- \Luminova\Exceptions\RouterException - Thrown if the method is used outside a CLI context, or if
$groupis empty or contains invalid characters.
Note: To register middleware with a group name, you must define your
guard()call within the correspondinggroup()closure.