phprouter
phprouter copied to clipboard
Single Route file for multiple controller files/classes
Refer to the code below, it seems that I have to call Router
class for each controller class and if I have two components in my system: Users and Product so I will have to replicate the below code for each class, is this true? How come I come up with a separate routes.php
file similar to Laravel by using your code?
use MiladRahimi\PhpRouter\Router;
class UsersController
{
function index()
{
return 'Class: UsersController & Method: index';
}
function handle()
{
return 'Class UsersController.';
}
}
$router = Router::create();
// Controller: Class=UsersController Method=index()
$router->get('/method', [UsersController::class, 'index']);
// Controller: Class=UsersController Method=handle()
$router->get('/class', UsersController::class);
$router->dispatch();
You can either keep all your routes in one routes.php file or split them into separate files and include them in your index.php. Just make sure you have only one router instance that you pass to these files. I recommend using a single routes.php file for simplicity.
routes.php:
use MiladRahimi\PhpRouter\Router;
use Laminas\Diactoros\Response\JsonResponse;
$router = Router::create();
$router->get('/users', [UsersController::class, 'index']);
$router->get('/users/{id}', [UsersController::class, 'show']);
$router->get('/products', [ProductsController::class, 'index']);
$router->get('/products/{id}', [ProductsController::class, 'show']);
$router->dispatch();
UsersController.php:
class UsersController
{
function index()
{
return [];
}
function show(int $id)
{
return $id;
}
}
ProductsController.php:
class ProductsController
{
function index()
{
return [];
}
function show(int $id)
{
return $id;
}
}