Reputation: 844
I'm using Symfony\Component\Serializer\Serializer, and I'm not sure what the difference between the serialize
and encode
methods is. They have identical signatures, and in practice they seem to give identical output.
Upvotes: 0
Views: 970
Reputation: 1324
The serialize method of the Symfony Serializer is a wrapper on its encode method. Note that you can call the encode method separately. The serialize method can call the normalize method before the encode method depending on the fact that the requested encoder (eg: json) needs normalization or not. If you intend to do a JSON serialization, the encode method of the serializer will eventually call json_encode PHP native method. And this method performs a serialization in fact...
For example, if you look into the jsonSerialize method of the jsonSerializable native class of PHP, you can read in the description:
Serializes the object to a value that can be serialized natively by json_encode().
So, at least, in the case of the JSON format, we can say that encoding is serializing in fact but in lower level.
If you call the encode method directly without using the serialize method, you will serialize your data into the expected format but will not take benefits of the normalize process if needed.
Upvotes: 2
Reputation: 20201
Based on the official docs, serializing involves two phases: normalizing and encoding. Normalizing converts input data into array, while encoding crunches that array down to desirable format (be it JSON
, XML
or something else).
Upvotes: 3