Serialize Library

Overview

This library provides a secure way of serializing and unserializing strings, integers, floats, booleans, and arrays.

Magento’s Serialize library provides the Magento\Framework\Serialize\SerializerInterface and the Json and Serialize implementations for serializing data.

Serialization

The main purpose of data serialization is to convert data into a string using serialize() to store in a database, a cache, or pass onto another layer in the application.

The other half of this process uses the unserialize() function to reverse the process and convert a serialized string back into string, integer, float, boolean, or array data.

For security reasons, SerializerInterface implementations, such as the Json and Serialize classes, should not serialize and unserialize objects.

Implementations

Json (default)

The Magento\Framework\Serialize\Serializer\Json class serializes and unserializes data using the JSON format. This class does not unserialize objects.

Serialize

The Magento\Framework\Serialize\Serializer\Serialize class is less secure than the Json implementation but provides better performance on large arrays. This class does not unserialize objects in PHP 7.

Magento discourages using the Serialize implementation directly because it can lead to security vulnerabilities. Always use the SerializerInterface for serializing and unserializing.

Usage

Declare SerializerInterface as a constructor dependency to get an instance of a serializer class.

use Magento\Framework\Serialize\SerializerInterface;

...

/**
 * @var SerializerInterface
 */
private $serializer;

...

public function __construct(SerializerInterface $serializer) {
  $this->serializer = $serializer;
}


The following example shows how to use a serializer’s serialize() and unserialize() functions to store and retrieve array data from a cache:

...

/**
 * @var string
 */
private $cacheId = 'mySerializedData';

...

/**
 * Save data to cache
 * @param array $data
 *
 * @return bool
 */
public function saveDataToCache($data)
{
  return $this->getCache()->save($this->serializer->serialize($data), $this->cacheId);
}

...

/**
 * Load data from cache
 *
 * @return array
 */
public function loadDataFromCache()
{
  $data = $this->getCache()->load($this->cacheId);
  if (false !== $data) {
    $data = $this->serializer->unserialize($data);
  }
  return $data;
}

...