You typically add a route for your action like below:
'test' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/test',
'defaults' => array(
'module' => '__NAMESPACE__',
'controller' => '__NAMESPACE__\Controller\Test',
'action' => 'index',
),
),
),
To make the __NAMESPACE__
constant work, add the following line to the beginning of your module's config:
namespace Member;
Extracting Parameters from Route
On route match, the router (top-level route class) returns
some parameters: the "defaults" (parameters listed in the defaults
section of
routing configuration) plus any wildcard parameters extracted from URL string.
To retrieve a parameter from the route in your controller's action method,
you typically use the Params
controller plugin and its fromRoute()
method,
which takes two arguments: the name of the parameter to retrieve and the value to
return if the parameter is not present.
The fromRoute()
method can also be used to retrieve all parameters at once as an array.
To do that, call the fromRoute()
without arguments, as shown in the example below:
// An example action.
public function indexAction() {
// Get the single 'id' parameter from route.
$id = $this->params()->fromRoute('id', -1);
// Get all route parameters at once as an array.
$params = $this->params()->fromRoute();
//...
}
Retrieving the RouteMatch and the Router Object
On route match, the router class internally creates an instance of Zend\Mvc\Router\RouteMatch
class,
providing the methods for extracting the matched route name and parameters extracted from route.
To get the RouteMatch
object from your controller's action method, you can use the following
code:
// An example action.
public function indexAction() {
// Get the RouteMatch object.
$routeMatch = $this->getEvent()->getRouteMatch();
// Get matched route's name.
$routeName = $routeMatch->getMatchedRouteName();
// Get all route parameters at once as an array.
$params = $routeMatch->getParams();
//...
}
For additional information about ZF2 routing, I would recommend reading the Using Zend Framework 2 book.