rest - Yii2 Rest API 自定义操作响应中的分页链接

标签 rest pagination yii2 api-design

我在 yii Rest Controller 中创建了自己的对象/索引操作,它做了一些简单的事情:

public function actionIndex($name){
                $query = Object::find();
                $count = $query->count();
               
                $pagination = new Pagination(['totalCount'=>$count]);
                $objectList = $query->offset($pagination->offset)->limit($pagination->limit)->all();
                return $objectList;
    }

当我向 http://localhost:8443/v0/objects?name=warehouse&page=1&per-page=1 发出请求时,我收到以下响应:

[
    {
        "id": 2,
        "data": {
            "city": "Test",
            "name": "ABC Warehouse",
            "postal_code": "M1F 4F2",
            "street_address": "1234 Street",
            "owner": 76,
            "created_at": "2016-09-23 15:10:20",
            "updated_at": "2017-07-27 11:56:15",
            "created_by": 9,
            "updated_by": 13
        },
        "displayData": []
    }
]

我想包含此处所示的分页链接信息,但不知道如何进行此操作 http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html

HTTP/1.1 200 OK
...
X-Pagination-Total-Count: 1000
X-Pagination-Page-Count: 50
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self, 
      <http://localhost/users?page=2>; rel=next, 
      <http://localhost/users?page=50>; rel=last

最佳答案

我假设您正在使用 yii\rest\ActiveController

快速浏览 yii2 源代码表明(对我来说)无论返回什么都需要实现 yii\data\DataProviderInterface。现在,您的代码根本不返回要处理的 Pagination 对象。

假设您的对象扩展了 ActiveRecord,请在您的操作中尝试此操作...

public function actionIndex($name){
    $query = Object::find();  // Assumes Object extends ActiveRecord
    $countQuery = clone $query;  // Good idea to clone query
    $count = $countQuery->count();
    $pagination = new Pagination(['totalCount'=>$count]);
    $query->offset($pagination->offset)->limit($pagination->limit);        
    return new ActiveDataProvider([
        'query' => $query,
        'pagination' => $pagination,        
    ]);
}

请注意,此代码未经测试。希望无论如何都会有帮助。

--- 编辑 ---

还在 yii\rest\ActiveController 中设置此属性(按照 Scott 的建议)

public $serializer = [
    'class' => 'yii\rest\Serializer',
    'collectionEnvelope' => 'items',
];

关于rest - Yii2 Rest API 自定义操作响应中的分页链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46120058/

相关文章:

mysql - 在yii2中选择最后一条记录之前

php - 在 yii2 中显示多个相关数据

java - 使用 mockito 的 restful 客户端的 Junit 测试用例

filter - 使用微服务架构进行分页或过滤数据的策略有哪些?

javascript - 将 Laravel 分页与 Ajax 请求结合使用

pagination - 在一个安静的 url 上编码分页信息的标准方法得到了吗?

php - Yii swiftmailer 无法在实时服务器上工作

javascript - 如何从 Node.js 服务器读取 json 响应?

rest - 如何在 IntelliJ IDEA 中使用 "Test restful web service"选项测试 RESTful Web 服务

rest - HBase 和 Elasticsearch 集成,如 MongoDB River