Skip to content

Conversation

CodeWithKyrian
Copy link

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.

- Fixed PHPStan error in Container::callableMethod by adding assertion for object type
- Added test cases for callableMethod error handling with nonexistent classes and loading failures
- Improved overall test coverage for Container class to 100%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant