简体   繁体   中英

How do I override the REST serializer in Yii2?

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, ie the same level as "items" and "_links". How and where do I do that?

Thank you.

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',
    ];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM