根据 Zend Framework 2 中的请求类型在同一路由上触发不同的操作


Triggering different actions on same route based on request type in Zend Framework 2

我正在尝试让 ZF2 以 REST 方式响应不同的请求类型。

在我的模块配置中.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',
                ),
            ),
        ),
    ),
),

在前端,我使用骨干网根据用户交互向服务器发送获取、发布、删除请求。当用户触发操作删除 id 为 n 的学生时,主干将使用 DELETE 请求发送/somePath/student/n。当用户触发操作以获取 id 为 n 的学生时,主干将使用 GET 请求发送/somePath/student/n。

如果

我希望当前设置正常工作,如果我想删除具有该 id 的学生,则必须更改 Backbone 请求并将 URL 从学生/n 更改为学生/删除/n,并且对于 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);
        }
    });
});

在服务器端的控制器中,我想为不同的请求类型运行不同的操作方法。

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

有一个名为 A complex example with child routes 的示例,其中文本路由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...
            ),
        ),
    ),
),

您可以使用 Zend''Mvc''Controller''AbstractRestfulController

它将根据HTTP请求方法调用某些函数

class StudentRest extends AbstractRestfulController {
    /** 
     * will be called with a GET request when it detects that route
     * matches paramater id has been set
     */
    public function get($id) {
        /*load studentdata*/
        return new JsonModel($data);
    }
    /**
     * Will be called on a POST request, and data should be sent with a $_POST
     * This should create a new object/row in db and return 201
     */
   public function Create($data) {
       /*create student*/
       $this->response->setStatusCode(201); // if new student was created.
       return JsonModel();
   }
    /**
     * Will be called on a PUT request. Data should be sent via $_POST
     * It also requires that the $id parameter is set in the route match
     */
   public function Update($id, $data) {}
    /**
     * Will be called on a DELETE request, It requires that the $id parameter is set in the route match
     */
   public function Delete($id) {}
}

有了它,您只需通过路由链接到控制器

即可
'student' => array(
        'type'    => 'segment',
        'options' => array(
            'route'    => '/student[/:id]',
            'constraints' => array(
                'id'     => '[0-9]+',
            ),
            'defaults' => array(
                'controller' => 'Student'Controller'StudentRest ',
            ),
        ),
    ),

getList 还有一些函数,当路由参数中没有提供$id时,将调用该函数。还值得一提的是,所有函数的默认实现都返回带有 ['content' => '方法不允许'] 的 405

文档如何使用它

根据文档:http://framework.zend.com/manual/1.12/en/zend.controller.request.html

确定请求方法

getMethod() 允许您确定用于请求当前资源的 HTTP 请求方法。此外,还有多种方法允许您在询问是否发出特定类型的请求时获得布尔响应:

isGet()
isPost()
isPut()
isDelete()
isHead()
isOptions()

这些的主要用例是创建RESTful MVC架构。