Skip to content

Add support for controller method pairs in routing #279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

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