正如文档所说:
[[yii\rest\IndexAction|index]]: list resources page by page
回应有观点:
curl -i -H "Accept:application/json" "http://192.168.100.5/index.php/tweets"
HTTP/1.1 200 OK
Date: Wed, 30 Mar 2016 12:10:07 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.14
X-Pagination-Total-Count: 450
X-Pagination-Page-Count: 23
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://192.168.100.5/tweets?page=1>; rel=self, <http://192.168.100.5/tweets?page=2>; rel=next, <http://192.168.100.5/tweets?page=23>; rel=last
Content-Length: 4305
Content-Type: application/json; charset=UTF-8
[{"id":71,"text":"Juíza do RS Graziela Bünd.......
我有一个返回的组件 - 一些数组(从两个表中选择)。如果我自定义indexAction。
public function actions()
{
$actions = parent::actions();
unset($actions['update']);
unset($actions['delete']);
unset($actions['view']);
unset($actions['index']);
return $actions;
}
public function actionIndex($count = 10)
{
/** @var TweetLastfinder $tweetLastFinder */
$tweetLastFinder = Yii::$app->get('tweetlastfinder');
return $tweetLastFinder->findLastTweets($count);
}
响应内容正确但有视图:
curl -i -H "Accept:application/json" "http://192.168.100.5/index.php/tweets"
HTTP/1.1 200 OK
Date: Wed, 30 Mar 2016 12:15:36 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.14
Content-Length: 2282
Content-Type: application/json; charset=UTF-8
[{"id":605,"text":"Popular Mus......
在这种情况下,我无法使用$serializer
,显示_meta
等
我想逐页使用组件和列表资源的响应,因为它执行默认操作。应该如何正确地完成?
答案 0 :(得分:1)
要充分利用内置的yii\rest\Serializer并显示_meta
或让您的网址如下所示:
/tweets?page=5&per-page=12&sort=name
您的操作应返回实现data provider的DataProviderInterface对象,该对象可以是以下任何一个:
所以这一切都取决于返回的$tweetLastFinder->findLastTweets()
对象类型。如果findLastTweets
方法返回ActiveQuery
对象,例如:
public function findLastTweets($count)
{
...
return $Tweets::find();
}
然后将其放入ActiveDataProvider
实例:
use yii\data\ActiveDataProvider;
public function actionIndex($count = 10)
{
/** @var TweetLastfinder $tweetLastFinder */
$tweetLastFinder = Yii::$app->get('tweetlastfinder');
$tweets = $tweetLastFinder->findLastTweets();
return new ActiveDataProvider([
'query' => $tweets,
]);
}
如果它返回一个数据数组或者你可以转换为数组的东西,那么只需将它放入ArrayDataProvider
实例。如果它是一个更复杂的对象,那么您需要构建一个自定义数据提供程序,您可以在其中包装它。了解如何在相关docs中执行此操作。