# Serializer

> Serializer converts resource objects and collections into array representation.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [rest](/docs/api/yii/rest/index.md) › Serializer

| class | `yii\rest\Serializer` |
| --- | --- |
| Extends | [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/rest/Serializer.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/rest/Serializer.php#L34) |

Serializer converts resource objects and collections into array representation.

Serializer is mainly used by REST controllers to convert different objects into array representation
so that they can be further turned into different formats, such as JSON, XML, by response formatters.

The default implementation handles resources as [`Model`](/docs/api/yii/base/model/index.md) objects and collections as objects
implementing [`DataProviderInterface`](/docs/api/yii/data/dataproviderinterface/index.md). You may override [`serialize()`](/docs/api/yii/rest/serializer/index.md#method-serialize) to handle more types.

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`$collectionEnvelope`](#property-collectionEnvelope) | `string\|null` | The name of the envelope (e.g. `items`) for returning the resource objects in a collection. Default: `null`. | `Serializer` |
| [`$currentPageHeader`](#property-currentPageHeader) | `string` | The name of the HTTP header containing the information about the current page number (1-based). Default: `'X-Pagination-Current-Page'`. | `Serializer` |
| <span id="property-expandParam"></span>`$expandParam` | `string` | The name of the query parameter containing the information about which fields should be returned in addition to those listed in [`$fieldsParam`](/docs/api/yii/rest/serializer/index.md#property-fieldsParam) for a resource object. Default: `'expand'`. | `Serializer` |
| [`$fieldsParam`](#property-fieldsParam) | `string` | The name of the query parameter containing the information about which fields should be returned for a [`Model`](/docs/api/yii/base/model/index.md) object. Default: `'fields'`. | `Serializer` |
| [`$linksEnvelope`](#property-linksEnvelope) | `string` | The name of the envelope (e.g. `_links`) for returning the links objects. Default: `'_links'`. Available since 2.0.4. | `Serializer` |
| [`$metaEnvelope`](#property-metaEnvelope) | `string` | The name of the envelope (e.g. `_meta`) for returning the pagination object. Default: `'_meta'`. Available since 2.0.4. | `Serializer` |
| [`$pageCountHeader`](#property-pageCountHeader) | `string` | The name of the HTTP header containing the information about total number of pages of data. Default: `'X-Pagination-Page-Count'`. | `Serializer` |
| [`$perPageHeader`](#property-perPageHeader) | `string` | The name of the HTTP header containing the information about the number of data items in each page. Default: `'X-Pagination-Per-Page'`. | `Serializer` |
| [`$preserveKeys`](#property-preserveKeys) | `bool` | Whether to preserve array keys when serializing collection data. Default: `false`. Available since 2.0.10. | `Serializer` |
| [`$request`](#property-request) | [`yii\web\Request`](/docs/api/yii/web/request/index.md)`\|null` | The current request. Default: `null`. | `Serializer` |
| [`$response`](#property-response) | [`yii\web\Response`](/docs/api/yii/web/response/index.md)`\|null` | The response to be sent. Default: `null`. | `Serializer` |
| [`$totalCountHeader`](#property-totalCountHeader) | `string` | The name of the HTTP header containing the information about total number of data items. Default: `'X-Pagination-Total-Count'`. | `Serializer` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/component/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__clone"></span>[`__clone()`](/docs/api/yii/base/component/index.md#method-__clone) | This method is called after the object is created by cloning an existing one. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/component/index.md#method-__get) | Returns the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/component/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/component/index.md#method-__set) | Sets the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/component/index.md#method-__unset) | Sets a component property to be null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehavior"></span>[`attachBehavior()`](/docs/api/yii/base/component/index.md#method-attachBehavior) | Attaches a behavior to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehaviors"></span>[`attachBehaviors()`](/docs/api/yii/base/component/index.md#method-attachBehaviors) | Attaches a list of behaviors to the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-behaviors"></span>[`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) | Returns a list of behaviors that this component should behave as. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/component/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/component/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-detachBehavior"></span>[`detachBehavior()`](/docs/api/yii/base/component/index.md#method-detachBehavior) | Detaches a behavior from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-detachBehaviors"></span>[`detachBehaviors()`](/docs/api/yii/base/component/index.md#method-detachBehaviors) | Detaches all behaviors from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-ensureBehaviors"></span>[`ensureBehaviors()`](/docs/api/yii/base/component/index.md#method-ensureBehaviors) | Makes sure that the behaviors declared in [`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) are attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehavior"></span>[`getBehavior()`](/docs/api/yii/base/component/index.md#method-getBehavior) | Returns the named behavior object. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehaviors"></span>[`getBehaviors()`](/docs/api/yii/base/component/index.md#method-getBehaviors) | Returns all behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasEventHandlers"></span>[`hasEventHandlers()`](/docs/api/yii/base/component/index.md#method-hasEventHandlers) | Returns a value indicating whether there is any handler attached to the named event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/component/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/component/index.md#method-hasProperty) | Returns a value indicating whether a property is defined for this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`init()`](#method-init) | Initializes the object. | `Serializer` |
| <span id="method-off"></span>[`off()`](/docs/api/yii/base/component/index.md#method-off) | Detaches an existing event handler from this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-on"></span>[`on()`](/docs/api/yii/base/component/index.md#method-on) | Attaches an event handler to an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`serialize()`](#method-serialize) | Serializes the given data into a format that can be easily turned into other formats. | `Serializer` |
| <span id="method-trigger"></span>[`trigger()`](/docs/api/yii/base/component/index.md#method-trigger) | Triggers an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`addPaginationHeaders()`](#method-addPaginationHeaders) protected | Adds HTTP headers about the pagination to the response. | `Serializer` |
| [`getRequestedFields()`](#method-getRequestedFields) protected |  | `Serializer` |
| [`serializeDataProvider()`](#method-serializeDataProvider) protected | Serializes a data provider. | `Serializer` |
| [`serializeModel()`](#method-serializeModel) protected | Serializes a model object. | `Serializer` |
| [`serializeModelErrors()`](#method-serializeModelErrors) protected | Serializes the validation errors in a model. | `Serializer` |
| [`serializeModels()`](#method-serializeModels) protected | Serializes a set of models. | `Serializer` |
| [`serializePagination()`](#method-serializePagination) protected | Serializes a pagination into an array. | `Serializer` |

## Property details

### $collectionEnvelope <span id="property-collectionEnvelope"></span>

```php
public string|null $collectionEnvelope = null
```

The name of the envelope (e.g. `items`) for returning the resource objects in a collection.

This is used when serving a resource collection. When this is set and pagination is enabled, the serializer
will return a collection in the following format:

```
[
    'items' => [...],  // assuming collectionEnvelope is "items"
    '_links' => {  // pagination links as returned by Pagination::getLinks()
        'self' => '...',
        'next' => '...',
        'last' => '...',
    },
    '_meta' => {  // meta information as returned by Pagination::toArray()
        'totalCount' => 100,
        'pageCount' => 5,
        'currentPage' => 1,
        'perPage' => 20,
    },
]
```

If this property is not set, the resource arrays will be directly returned without using envelope.
The pagination information as shown in `_links` and `_meta` can be accessed from the response HTTP headers.

### $currentPageHeader <span id="property-currentPageHeader"></span>

```php
public string $currentPageHeader = 'X-Pagination-Current-Page'
```

The name of the HTTP header containing the information about the current page number (1-based).

This is used when serving a resource collection with pagination.

### $fieldsParam <span id="property-fieldsParam"></span>

```php
public string $fieldsParam = 'fields'
```

The name of the query parameter containing the information about which fields should be returned for a [`Model`](/docs/api/yii/base/model/index.md) object.

If the parameter is not provided or empty, the default set of fields as defined
by [`Model::fields()`](/docs/api/yii/base/model/index.md#method-fields) will be returned.

### $linksEnvelope <span id="property-linksEnvelope"></span>

```php
public string $linksEnvelope = '_links'
```

The name of the envelope (e.g. `_links`) for returning the links objects.

It takes effect only, if `collectionEnvelope` is set.

**Since**

2.0.4

### $metaEnvelope <span id="property-metaEnvelope"></span>

```php
public string $metaEnvelope = '_meta'
```

The name of the envelope (e.g. `_meta`) for returning the pagination object.

It takes effect only, if `collectionEnvelope` is set.

**Since**

2.0.4

### $pageCountHeader <span id="property-pageCountHeader"></span>

```php
public string $pageCountHeader = 'X-Pagination-Page-Count'
```

The name of the HTTP header containing the information about total number of pages of data.

This is used when serving a resource collection with pagination.

### $perPageHeader <span id="property-perPageHeader"></span>

```php
public string $perPageHeader = 'X-Pagination-Per-Page'
```

The name of the HTTP header containing the information about the number of data items in each page.

This is used when serving a resource collection with pagination.

### $preserveKeys <span id="property-preserveKeys"></span>

```php
public bool $preserveKeys = false
```

Whether to preserve array keys when serializing collection data.

Set this to `true` to allow serialization of a collection as a JSON object where array keys are
used to index the model objects. The default is to serialize all collections as array, regardless
of how the array is indexed.

**Since**

2.0.10

### $request <span id="property-request"></span>

```php
public yii\web\Request|null $request = null
```

The current request.

If not set, the `request` application component will be used.

### $response <span id="property-response"></span>

```php
public yii\web\Response|null $response = null
```

The response to be sent.

If not set, the `response` application component will be used.

### $totalCountHeader <span id="property-totalCountHeader"></span>

```php
public string $totalCountHeader = 'X-Pagination-Total-Count'
```

The name of the HTTP header containing the information about total number of data items.

This is used when serving a resource collection with pagination.

## Method details

### init() <span id="method-init"></span>

```php
public function init(): mixed
```

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the
given configuration.

**Returns**

`mixed`

### serialize() <span id="method-serialize"></span>

```php
public function serialize(mixed $data): mixed
```

Serializes the given data into a format that can be easily turned into other formats.

This method mainly converts the objects of recognized types into array representation.
It will not do conversion for unknown object types or non-object data.
The default implementation will handle [`Model`](/docs/api/yii/base/model/index.md), [`DataProviderInterface`](/docs/api/yii/data/dataproviderinterface/index.md) and [\JsonSerializable](https://www.php.net/manual/en/class.jsonserializable.php).
You may override this method to support more object types.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$data` | `mixed` | The data to be serialized. |

**Returns**

`mixed`: The converted data.

### addPaginationHeaders() <span id="method-addPaginationHeaders"></span>

```php
protected function addPaginationHeaders(yii\data\Pagination $pagination): mixed
```

Adds HTTP headers about the pagination to the response.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$pagination` | [`yii\data\Pagination`](/docs/api/yii/data/pagination/index.md) |  |

**Returns**

`mixed`

### getRequestedFields() <span id="method-getRequestedFields"></span>

```php
protected function getRequestedFields(): array
```

**Returns**

`array`: The names of the requested fields. The first element is an array representing the list of default fields requested, while the second element is an array of the extra fields requested in addition to the default fields.

**See also**

- [`Model::fields()`](/docs/api/yii/base/model/index.md#method-fields)
- [`Model::extraFields()`](/docs/api/yii/base/arrayabletrait/index.md#method-extraFields)

### serializeDataProvider() <span id="method-serializeDataProvider"></span>

```php
protected function serializeDataProvider(yii\data\DataProviderInterface $dataProvider): array|null
```

Serializes a data provider.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$dataProvider` | [`yii\data\DataProviderInterface`](/docs/api/yii/data/dataproviderinterface/index.md) |  |

**Returns**

`array|null`: The array representation of the data provider.

### serializeModel() <span id="method-serializeModel"></span>

```php
protected function serializeModel(yii\base\Arrayable $model): array|null
```

Serializes a model object.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$model` | [`yii\base\Arrayable`](/docs/api/yii/base/arrayable/index.md) |  |

**Returns**

`array|null`: The array representation of the model

### serializeModelErrors() <span id="method-serializeModelErrors"></span>

```php
protected function serializeModelErrors(yii\base\Model $model): array
```

Serializes the validation errors in a model.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$model` | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |  |

**Returns**

`array`: The array representation of the errors

### serializeModels() <span id="method-serializeModels"></span>

```php
protected function serializeModels(array $models): array
```

Serializes a set of models.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$models` | `array` |  |

**Returns**

`array`: The array representation of the models

### serializePagination() <span id="method-serializePagination"></span>

```php
protected function serializePagination(yii\data\Pagination $pagination): array
```

Serializes a pagination into an array.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$pagination` | [`yii\data\Pagination`](/docs/api/yii/data/pagination/index.md) |  |

**Returns**

`array`: The array representation of the pagination

**See also**

- [`addPaginationHeaders()`](/docs/api/yii/rest/serializer/index.md#method-addPaginationHeaders)