twoh / cli-router
This project implements a simple CLI router in PHP. It allows registering and handling routes that can be called via PHP.
Requires
- php: ^8.3
Requires (Dev)
- ext-xdebug: *
- phpunit/phpunit: ^11
- roave/security-advisories: dev-latest
- twoh/logger: ^1
- twoh/security-check: ^1
- twoh/validator: ^1
README
About CLI-Router
This project implements a simple CLI router in PHP. It allows registering and handling routes that can be called via PHP.
Requirements
- PHP 8.3 or higher
- Composer
Installation
composer req twoh/cli-router
Usage
Starting Docker
To start the Docker containers, navigate to the project directory and use the following command:
docker-compose up -d --build
Docker Containers
Docker Container Name | Final Container Name | Purpose |
---|---|---|
php |
cli_router_php83_container |
PHP 8.3 Environment |
Custom Route Example
Here is an example of a custom route:
<?php declare(strict_types=1); namespace TWOH\CliRouter\Routes; class HelloWorldRoute implements RouteInterface { public function __invoke(): void { echo 'Hello World' . PHP_EOL; } }
Registering Routes
Routes can now be registered in a configuration file. Here is an example of a configuration file cli-routes.php
:
use TWOH\CliRouter\Routes\HelloWorldRoute; return [ 'v1' => [ 'hello' => [ 'world' => new HelloWorldRoute() ], 'hello2' => [ 'world' => new HelloWorldRoute() ] ], 'v2' => [ 'hello3' => [ 'world' => new HelloWorldRoute() ], 'hello4' => [ 'world' => new HelloWorldRoute() ] ], ];
Custom Functions
You can also instantiate the router and register routes using the boot function. You can specify a custom configuration path if needed:
Boot Function
(new \TWOH\CliRouter\Services\RouterService())->boot(__DIR__ . '/../config/cli-routes.php');
Call Route
To call a route, navigate to the project directory and use the following command:
Directly over Method call
use TWOH\CliRouter\Services\RouterService; $router = new RouterService(); $router->boot(__DIR__ . '/../config/cli-routes.php'); $router->call('v1-hello-world');
php src/cli.php
Directly over Cli call
use TWOH\CliRouter\Services\RouterService; $router = new RouterService(); $router->boot(__DIR__ . '/../config/cli-routes.php'); $router->call();
php src/cli.php v1-hello-world
Running Tests
To verify that the tests are passing, run the following command:
vendor/bin/phpunit
Logging
This project uses its own LoggerTrait
class. You can integrate it into your classes to log messages as follows:
use LoggerTrait; $this->info('Your message here'); $this->warning('Your message here'); $this->error('Your message here');
The log files will be stored in the logs
folder.