php - How does Symfony2 passes the parameter of a URI to the controller Action method? -
i have started learning symfony2. came across doubt: if have route:
# app/config/routing.yml hello: path: /hello/{name} defaults: { _controller: acmehellobundle:hello:index }
and controller:
// src/acme/hellobundle/controller/hellocontroller.php namespace acme\hellobundle\controller; use symfony\component\httpfoundation\response; class hellocontroller { public function indexaction($name) { return new response('<html><body>ciao '.$name.'!</body></html>'); } }
internally symfony2 (inside app/bootstrap.php.cache) calls call user_func_array() php built-in function:
$arguments = $this->resolver->getarguments($request, $controller); $response = call_user_func_array($controller, $arguments);
and call getarguments() method returns array of arguments pass action method. if controller were:
// src/acme/hellobundle/controller/hellocontroller.php namespace acme\hellobundle\controller; use symfony\component\httpfoundation\response; class hellocontroller { public function indexaction($n) { return new response('<html><body>ciao '.$n.'!</body></html>'); } }
symfony have complained runtimeexception because no param $n set.
my question is: how symfony controls behaviour, mean, if route has {name} param, why controller must have action method $name parameter , parameter must called $name?
cause in plain php, work:
$name = 'alex'; function indexaction($n) { echo $n; } $f = 'indexaction'; $arguments = array($name); call_user_func_array($f, $arguments);
even if functions signature accepts param named $n , not $name.
i hope question understandable, if not, please tell me , make edit.
thanks attention!
it's done in controller resolver httpkernel/controller/controllerresolver.php via getarguments()
& doarguments()
.
for better understanding, find need in getting controller arguments
edit: answer comment.
does symfony use reflectionparameter class internally in order keep track of params of method's signature , match them route params?
yes, controllerresolver uses:
reflectionmethod keep track of params of method's signature if
$controller
methodreflectionobject if
$controller
objectreflectionfunction if
$controller
function
here how:
public function getarguments(request $request, $controller) { if (is_array($controller)) { $r = new \reflectionmethod($controller[0], $controller[1]); } elseif (is_object($controller) && !$controller instanceof \closure) { $r = new \reflectionobject($controller); $r = $r->getmethod('__invoke'); } else { $r = new \reflectionfunction($controller); } return $this->dogetarguments($request, $controller, $r->getparameters()); }
Comments
Post a Comment