我试图让 ZF2 以 REST 方式响应不同的请求类型。
在我的 module.config.php 中,我有这个路由器配置。
'router' => array(
'routes' => array(
'student' => array(
'type' => 'segment',
'options' => array(
'route' => '/student[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Student\Controller\Student',
'action' => 'index',
),
),
),
),
),
在前端,我使用 Backbone 根据用户交互向服务器发送 GET、POST、DELETE 请求。 当用户触发删除 id 为 n 的学生的操作时,backbone 将使用 DELETE 请求发送/somePath/student/n 。 当用户触发操作以获取 id 为 n 的学生时,backbone 将使用 GET 请求发送/somePath/student/n 。
如果我希望当前设置起作用,我必须更改 Backbone 请求并将 URL 从 Student/n 更改为 Student/delete/n(如果我想删除具有该 id 的学生),对于 GET 也类似。
这是我在客户端所做的,我想避免。
define(['backbone'], function(Backbone){
return Backbone.Model.extend({
defaults:{
//set default model values
},
initialize: function(){
//initialize
},
methodToURL: {
'delete': '/student/delete'
},
sync: function(method, model, options) {
options = options || {};
var id = arguments[1]['id']
options.url = model.methodToURL[method.toLowerCase()] + '/' + id;
return Backbone.sync.apply(this, arguments);
}
});
});
在服务器端的 Controller 中,我有不同的操作方法,我想针对不同的请求类型运行。
public function deleteAction()
{
//some code
}
public function getAction()
{
//some code
}
我不想更改默认的主干行为(拦截和更改请求)。
有没有办法将 ZF2 路由器配置为使用相同的路由,但根据请求方法类型触发不同的操作?
最佳答案
您可以使用Method
路由作为分段路由的子路由。 http://framework.zend.com/manual/2.3/en/modules/zend.mvc.routing.html
有一个名为带有子路由的复杂示例
的示例,其中blog
文字路由的作者创建子路由,每个子路由的类型都不同。
您只需在学生路由中创建子路由,该子路由将为您要使用的每种方法键入 Method
,然后仅更改此方法类型的操作。
'router' => array(
'routes' => array(
'student' => array(
'type' => 'segment',
'options' => array(
'route' => '/student[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Student\Controller\Student',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'delete' => array(
'type' => 'method',
'options' => array(
'verb' => 'delete',
'defaults' => array(
'action' => 'delete'
),
),
),
'put' => array(
'type' => 'method',
'options' => array(
'verb' => 'put',
'defaults' => array(
'action' => 'put'
),
),
),//and so on...
),
),
),
),
关于javascript - Zend Framework 2 中根据请求类型在同一路由上触发不同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26907283/