Skip to content
PHP Ecosystem
Explore

Serializer

API reference › yii › rest › Serializer

classyii\rest\Serializer
Extendsyii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/rest/Serializer.php

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 objects and collections as objects implementing DataProviderInterface. You may override serialize() to handle more types.

PropertyTypeDescriptionDefined by
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$collectionEnvelopestring|nullThe name of the envelope (e.g. items) for returning the resource objects in a collection. Default: null.Serializer
$currentPageHeaderstringThe name of the HTTP header containing the information about the current page number (1-based). Default: 'X-Pagination-Current-Page'.Serializer
$expandParamstringThe name of the query parameter containing the information about which fields should be returned in addition to those listed in $fieldsParam for a resource object. Default: 'expand'.Serializer
$fieldsParamstringThe name of the query parameter containing the information about which fields should be returned for a Model object. Default: 'fields'.Serializer
$linksEnvelopestringThe name of the envelope (e.g. _links) for returning the links objects. Default: '_links'. Available since 2.0.4.Serializer
$metaEnvelopestringThe name of the envelope (e.g. _meta) for returning the pagination object. Default: '_meta'. Available since 2.0.4.Serializer
$pageCountHeaderstringThe name of the HTTP header containing the information about total number of pages of data. Default: 'X-Pagination-Page-Count'.Serializer
$perPageHeaderstringThe name of the HTTP header containing the information about the number of data items in each page. Default: 'X-Pagination-Per-Page'.Serializer
$preserveKeysboolWhether to preserve array keys when serializing collection data. Default: false. Available since 2.0.10.Serializer
$requestyii\web\Request|nullThe current request. Default: null.Serializer
$responseyii\web\Response|nullThe response to be sent. Default: null.Serializer
$totalCountHeaderstringThe name of the HTTP header containing the information about total number of data items. Default: 'X-Pagination-Total-Count'.Serializer
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the object.Serializer
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
serialize()Serializes the given data into a format that can be easily turned into other formats.Serializer
trigger()Triggers an event.yii\base\Component
addPaginationHeaders() protectedAdds HTTP headers about the pagination to the response.Serializer
getRequestedFields() protectedSerializer
serializeDataProvider() protectedSerializes a data provider.Serializer
serializeModel() protectedSerializes a model object.Serializer
serializeModelErrors() protectedSerializes the validation errors in a model.Serializer
serializeModels() protectedSerializes a set of models.Serializer
serializePagination() protectedSerializes a pagination into an array.Serializer
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.

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.

public string $fieldsParam = 'fields'

The name of the query parameter containing the information about which fields should be returned for a Model object.

If the parameter is not provided or empty, the default set of fields as defined by Model::fields() will be returned.

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

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

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.

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.

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

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

The current request.

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

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

The response to be sent.

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

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.

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

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, DataProviderInterface and \JsonSerializable. You may override this method to support more object types.

Parameters

ParameterTypeDescription
$datamixedThe data to be serialized.

Returns

mixed: The converted data.

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

Adds HTTP headers about the pagination to the response.

Parameters

ParameterTypeDescription
$paginationyii\data\Pagination

Returns

mixed

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

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

Serializes a data provider.

Parameters

ParameterTypeDescription
$dataProvideryii\data\DataProviderInterface

Returns

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

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

Serializes a model object.

Parameters

ParameterTypeDescription
$modelyii\base\Arrayable

Returns

array|null: The array representation of the model

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

Serializes the validation errors in a model.

Parameters

ParameterTypeDescription
$modelyii\base\Model

Returns

array: The array representation of the errors

protected function serializeModels(array $models): array

Serializes a set of models.

Parameters

ParameterTypeDescription
$modelsarray

Returns

array: The array representation of the models

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

Serializes a pagination into an array.

Parameters

ParameterTypeDescription
$paginationyii\data\Pagination

Returns

array: The array representation of the pagination

See also