How to set up Hierarchical Zend Rest Routes?

耗尽温柔 提交于 2019-11-28 18:59:08

AFAIK, there is no feature in Zend_Rest_Route which allows you to do something like this. There is a proposal but not sure when it'll be implemented. You can add this in your Bootstrap to set up this custom route.

$front = $this->getResource('FrontController'); 
$testRoute = new Zend_Controller_Router_Route(
    'users/:user_id/items/:item_id',
    array(
        'controller' => 'users',
        'action' => 'item',
        'module' => 'default'
    )
);

$front->getRouter()->addRoute('test', $testRoute);

user_id or item_id become available in itemAction in UsersController as parameters:

$user_id = $this->_request->getParam('user_id');

I open sourced the solution into github and as a composer package. see https://github.com/aporat/Application_Rest_Controller_Route.

I added a new class which extends Zend_Controller_Router_Route and adds abiliy to add custom restful routes, such as

$frontController = Zend_Controller_Front::getInstance();
$frontController->getRouter()->addRoute('users-messages', new Application_Rest_Controller_Route($frontController, 'users/:user_id/messages', ['controller' => 'users-messages']));

Zend_Rest_Route maps the first parameter after the controller name to 'id' only when there is 1 parameter.

Best solution I've come up with is to subclass Zend_Rest_Route and override the match() function. Copy Zend_Rest_Route's match function, but add the following just before the "Digest URI Params" comment (about 60 lines in).

if($pathElementCount > 1 && $path[0] != 'id') {
    $params['id'] = urldecode($path[0]);
    array_shift($path);
}  

That should give you the functionality you're looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!