我想在zend框架3中创建一个具有两个参数的API路由。我将路线定义如下:
'api' => [
'child_routes' => [
/* api/users/<id> */
'users' => [
'type' => Segment::class,
'options' => [
'route' => '/users[/[:id]]',
'constraints' => [
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Api\Controller\UserController::class,
],
],
'may_terminate' => true,
'child_routes' => [
/* api/users/<uid>/documents/<id> */
'documents' => [
'type' => Segment::class,
'options' => [
'route' => '/documents[/:id]',
'constraints' => [
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Api\Controller\DocumentController::class,
],
],
],
]
]
]
我希望支持的路线是:
api/users
api/users/<user_id>
api/users/<user_id>/documents
api/users/<user_id>/documents/<document_id>
按照上述规则,当我将HTTP Get发送到api / users // documents时,它指的是“ DocumentsController.php”中的方法“ get”,而预计将调用方法“ getList”。
问题是我应该如何更改路由,我的资源定义是否遵循API设计原则?
答案 0 :(得分:0)
您还应该添加动作名称,您可以将动作名称与控制器一起添加。 因此,控件将转到“ api / users / documents”和“ index”“ api / users”的“ getList”
如下面的更新代码所示:
'api' => [
'child_routes' => [
/* api/users/<id> */
'users' => [
'type' => Segment::class,
'options' => [
'route' => '/users[/:id]',
'constraints' => [
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Api\Controller\UserController::class,
'action' => 'index',
],
],
'may_terminate' => true,
'child_routes' => [
/* api/users/<uid>/documents/<id> */
'documents' => [
'type' => Segment::class,
'options' => [
'route' => '/documents[/:id]',
'constraints' => [
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Api\Controller\DocumentController::class,
'action' => 'getList',
],
],
],
]
]
]