Reputation: 448
I've been playing around with Silex for the past couple of days. I'm having trouble understand how the following code snippet works.
I'm not interested in what it does but rather how it does it.
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
$app->get('/foo', function (Application $app, Request $request) {
$subRequest = Request::create('/', ...);
$response = $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
return $response;
});
I get confused around
function (Application $app, Request $request)
From my understanding that's an anonymous function being called as an argument to the $app->get method. How do the two arguments in this anonymous function work? specifically what's:
Application $app, Request $request
?
Thanks!
Upvotes: 1
Views: 615
Reputation: 28259
The implicit way that controller arguments get populated is probably one of the most confusing parts of silex.
When you define a controller via one of the HTTP verb methods, that controller can add type hints to its arguments. Request
and Application
are type hints for the two arguments $app
and $request
.
The HttpKernel
is the part of Silex responsible for invoking the controller. It uses a ControllerResolver
to figure out which arguments to pass in. The ControllerResolver
will infer the arguments from the type hints.
Silex\Application
type hint, it will inject the application.Symfony\Component\HttpFoundation\Request
type hint, it will inject the current request.If you want to get a better understanding, I recommend reading the HttpKernel source code.
Upvotes: 9