正如文档所说:[[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
等
我想使用来自组件的响应,并按默认操作逐页列出资源。应该如何正确地进行?
要充分利用内置的yii''rest''Serializer并显示_meta
或使您的URL看起来像:
/tweets?page=5&per-page=12&sort=name
您的操作应该返回一个实现DataProviderInterface的数据提供程序对象,该对象可以是以下任何对象:
- 活动数据提供者
- SQL数据提供者
- 数组数据提供者
- 或自定义数据提供者
所以这完全取决于$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
实例中即可。如果它是一个更复杂的对象,那么你需要构建一个自定义的数据提供程序,你可以在其中包装它。请参阅相关文档中的操作方法。