Request dependency injection in controllers
sanderdewijs opened this issue · 0 comments
I' m using PHRoute for a while now and it's awesome. Recently I combined it with PHP-DI for dependency injection. Thanks to the HandleResolverInterface this was quite easy to achieve.
Although dependency injection works great in the constructor, it would be nice if you could pass the request as Symfony\Component\HttpFoundation\Request in a controller method directly.
I tried this and while the class did get injected into the method by PHP-DI, it threw an exception in PHRoute because the controller method now had one parameter which was not defined or called in the route. Is there a way to handle this?
// Route
$router->get('/login', ['Controllers\LoginController','indexAction']);
// Controller
/**
* @throws \Twig_Error_Loader
* @throws \Twig_Error_Runtime
* @throws \Twig_Error_Syntax
* @Inject("Request")
*/
public function indexAction(Request $request)
{
$this->response->setContent($this->twig->render('login.html.twig', [
'bodyClass' => 'loginbackground',
'lang' => $this->lang,
]));
$this->response->sendContent();
}
Before implementing dependency injection I instantiated the request as a property in the BaseController class, which all other controllers extend. This way I could access the request using $this->request in every controller. However this felt a bit inefficient because perhaps a single request would be created in all other controllers while it is only needed in the controller that is actually called.