CakePHP Custom Rest Routing

410 Views Asked by At

Our router defines a custom parameter before the controller and action definition:

Router::connect(
    '/:store/:controller/:action/*',
    array(),
    array(
       'store' => 'shop\/[^\/]+'
    )
);

Router::mapResources('Invoices');
Router::parseExtensions();

It matches requests prefixed with '/shop/x' where x is an id:

http://host.com/shop/1/invoices/view/1  

However, the above definition doesn't route REST requests properly:

http://host.com/shop/1/invoices/1.json  (doesn't work)

As a workaround, it works by passing the action (which isn't ideal for REST however):

http://host.com/shop/1/invoices/view/1.json

Any ideas on how make the rest route work?

1

There are 1 best solutions below

0
On

There's a special key available for the third parameter of the connect function.

pass is used to define which of the routed parameters should be shifted into the pass array. Adding a parameter to pass will remove it from the regular route array. Ex. 'pass' => array('id')

Router::connect(
    '/:store/:controller/:id',
    array('[method]'=>'GET', 'action'=>'view'),
    array(
       'store' => 'shop\/[^\/]+',
       'id' => '[0-9]+',
       'pass' => array('id')
    )
);

Found the solution from the CakePHP Routing Documentation.