framework-x icon indicating copy to clipboard operation
framework-x copied to clipboard

Add support for controller method pairs in routing

Open CodeWithKyrian opened this issue 9 months ago • 0 comments

This PR adds support for using controller-method pairs in route definitions using array notation [Controller::class, 'method']. This enhancement allows developers to group related actions into controller classes while keeping the routing concise.

Changes

  • Added callableMethod in Container class to handle controllers with named methods
  • Enhanced RouteHandler::map to detect and support [ControllerClass::class, 'method'] syntax
  • Added comprehensive test coverage for both the new container method and routing functionality
  • Updated documentation to demonstrate the new capability

Benefits

  • Better code organization: Group related endpoints into a single controller class
  • Familiar syntax: Uses the standard PHP array callback notation
  • Fully backward compatible: All existing code and patterns continue to work
  • Middleware support: Controller methods can be used as both handlers and middleware

Example

// Before: 
$app->get('/users', UserListController::class);
$app->get('/users/{id}', UserShowController::class);
$app->post('/users', UserCreateController::class);
$app->delete('/users/{id}', UserDeleteController::class);

// After:
$app->get('/users', [UserController::class, 'index']);
$app->get('/users/{id}', [UserController::class, 'show']);
$app->post('/users', [UserController::class, 'create']);
$app->delete('/users/{id}', [UserController::class, 'delete']);

The implementation maintains the same dependency injection capabilities and performance characteristics as the existing approach with invokable controllers.

CodeWithKyrian avatar May 21 '25 09:05 CodeWithKyrian