Skip to content
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

Request dependency injection in controllers #75

Open
sanderdewijs opened this issue Jan 29, 2018 · 0 comments
Open

Request dependency injection in controllers #75

sanderdewijs opened this issue Jan 29, 2018 · 0 comments

Comments

@sanderdewijs
Copy link

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.

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

No branches or pull requests

1 participant