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.
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.
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
Magento discourages using the Serialize implementation directly because it can lead to security vulnerabilities.
Always use the
SerializerInterface for serializing and unserializing.
SerializerInterface as a constructor dependency to get an instance of a serializer class.
The following example shows how to use a serializer’s
unserialize() functions to store and retrieve array data from a cache:
Backward Compatibility Note
SerializerInterface interface and its implementations only exist since Magento version 2.2.
Because of this, it is not possible to use these classes in code that has to be compatible with Magento 2.1 or 2.0.
In code that is compatible with earlier versions of Magento 2, constructor dependency injection can not be used to get an instance of
Instead, a runtime check if the
SerializerInterface definition exists can made, and if it does, it can be instantiated by directly accessing the object manager using a static method. Alternatively a check against the Magento 2 version or the
magento/framework composer package version would work, too.
If the interface does not exist or an earlier version of Magento 2 is being executed, the appropriate native PHP serialization function has to be called, e.g.
\json_encode(), depending on the usercase.
Here is an example: