duanpo7282 2013-12-31 10:33
浏览 50
已采纳

Zend Framework 2 REST API:想要调用get()而不是getList()

I am building RESTful API in Zend Framework 2. My route is article/person. I know that if id is not passed in url then it will call getList() method, not get().

In my case, I don't pass id as a get or post parameter but I pass it in HTTP header. As I use id to perform database operations, I want it to call get() method, not getList(). How can I tweak the code to do that?

Is it possible to specify exact method name to call in routing?

  • 写回答

3条回答 默认 最新

  • douwen1213 2014-01-02 09:01
    关注

    I don't pass id as a get or post parameter but I pass it in HTTP header

    This does make your REST invalid, so it isn't actually REST anymore. You therefor cannot use the RestfulAbstractController without customization.

    You can either write your own abstract controller or you override the getIdentifier method:

    protected function getIdentifier($routeMatch, $request)
    {
        $identifier = $this->getIdentifierName();
        $headers    = $request->getHeaders();
    
        $id = $headers->get($identifier)->getFieldValue();
        if ($id !== false) {
            return $id;
        }
    
        return false;
    }
    

    Make sure you set the correct identifier name in each controller. In this case, the identifier name should match the name of the header you are using.

    Note this will be used for GET, PUT, PATCH, DELETE and HEAD requests, not only for GET!

    /edit:

    The getIdentifier method is called in the flow a controller determines which method to run. Normally, it's this:

    1. The controller is constructed
    2. The controller's dispatch is called (the controller is Dispatchable)
    3. The dispatch triggers an event "dispatch"
    4. The method onDispatch listens to this event
    5. In the AbstractRestfulController the method tries to determine which method to call

    For #5, it checks for example if the request is a GET request. If so, it checks if there is an identifier given. If so, the get() is used. If not, the getList() is used. The "if there is an identifier given" check is done with the getIdentifier() method.

    If you extend the AbstractRestfulController with your own abstract controller and override the getIdentifier(), you can determine your own identifier. This way, you can check for the header instead of the route parameter or query parameter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 动态规划算法实现背包问题
  • ¥15 wpf程序使用过程中异常奔溃
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少
  • ¥15 按颜色进行点云分割-python
  • ¥15 Matlab如何实现汽车变道切入场景的批量仿真