Reputation: 153
I'm building a REST API with Yii2. Normally the request response looks something like this:
{
"items": [
{
"id": 1,
...
},
{
"id": 2,
...
},
...
],
"_links": {
"self": {
"href": "http://localhost/users?page=1"
},
"next": {
"href": "http://localhost/users?page=2"
},
"last": {
"href": "http://localhost/users?page=50"
}
},
"_meta": {
"totalCount": 1000,
"pageCount": 50,
"currentPage": 1,
"perPage": 20
}
}
I want to override the serializer so that the fields contained in the "_meta" array are instead included in the root of the array, i.e. the same level as "items" and "_links". How and where do I do that?
Thank you.
Upvotes: 0
Views: 3342
Reputation: 2164
According to the documentation you create a new Serializer class. So, basically, you extend yii\rest\Serializer
and rewrite the serialize()
method. Then you set your custom serializer for your controller.
class MySerializer extends Serializer
{
public function serialize($data)
{
$d = parent::serialize($data);
$m = $d['_meta'];
unset($d['_meta']);
return array_merge($d, $m);
}
}
class MyController extends ActiveController
{
public $serializer = [
'class' => 'yii\rest\MySerializer',
'collectionEnvelope' => 'items',
];
}
Upvotes: 2