I'm trying to use a hierarchical resource in ZF2 for a Restful API. The resource should looks like clients/1/addresses
. What I've tried was this
'clients' => array(
'type' => 'segment',
'options' => array(
'route' => '/clients[/:id]',
'constraints' => array(
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Api\Controller\ClientController',
),
),
'may_terminate' => true,
'child_routes' => array(
'addresses' => array(
'type' => 'segment',
'options' => array(
'route' => '/addresses[/:address_id]',
'constraints' => array(
'address_id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Api\Controller\AddressController',
),
),
),
),
),
There is this conflict of both id's, but I don't know if I rename the route identifier id
of the resource addresses like I did will solve it. Anyway, the real problem is that the route clients/1/addresses
calls the get
method of the AddressController
, not the getList
, and I think that's because Zend understands that the id of the client belongs to addresses, so its calls the get method.
Do you know how to deal with this?
You are probably right that get
is called instead of getList
because of the id
being present in your route match parameters and the controller by default uses 'id'
for matching the route identifier.
The way to deal with this is that you give the route identifiers names that fit the resource. So for client you make client_id
and for address you use address_id
(like you already did).
And then you configure your AbstractRestfulController
instance to "look" for the correct route identifier using the setIdentifierName
method:
$clientController->setIdentifierName( 'client_id' );
$addressController->setIdentifierName( 'address_id' );
This is just an example, the best way to do this is (of course) by using a controller factory...