I am new to PHP frameworks and building REST API on Zend Framework 2. I want to add params to Request
. I could not find method to add params so I'll do it by getting all params then, adding new params to them and then setting this new set of params to Request
.
I get params using
$this->params()->fromQuery()
but, I don't find any way to set params back to Request
. Is there any method available for this?
EDIT : I tried below. Which is not giving desired result.
In Module.php :
public function onBootstrap(\Zend\Mvc\MvcEvent $e)
{
$em = $e->getApplication()->getEventManager();
echo "Outside";
$em->attach (MvcEvent::EVENT_DISPATCH, function(MvcEvent $e) {
echo "Inside";
$routeMatch = $e->getRouteMatch();
$routeMatch->setParam("myParam", "paramValue");
});
}
In my controller :
echo "myParam : " . $this->params()->fromQuery('myParam');
Param value is null
when I get it. This is on account of controller code is executed first(where I get param value) and then the Dispatch
event is triggered(where I add param to RouteMatch).
Outside
myParam :
Inside
Probably you don't need to add params to the request, and you can achieve the same adding params to the routeMatch (this is, the object tha represents the route that the current requests matches). I do this every now and then.
I use to do it in the Module.php, in the onBootstrap function. UPDATE: Attaching some code to the EVENT_ROUTE
public function onBootstrap(MvcEvent $e) {
$em = $e->getApplication ()->getEventManager ();
$em->attach ( MvcEvent::EVENT_ROUTE, function(MvcEvent $e) {
$routeMatch = $e->getRouteMatch();
$params = //your params, as an array
foreach($params as $key => $value)
$routeMatch->setParam($k, $v);
});
}