If you’re used to working with models (in any foundation or framework, but specifically WordPress), then there’s a chance that you may need to serialize an instance of the model at some point.
Sure, writing the class to a database using PHP’s built-in functions is easy enough; however, introducing a bit of flexibility especially as it relates to making it available on other platforms is important.
For example, let’s say you’re building an application on WordPress that’s going to have some type of unique piece of information represented in a model. The model will then be accessible via a mobile application through the REST API.
Arguably, one of the easiest ways to get this done is to use JSON. It’s a format that works across various languages and platforms, can be easily serialized and de-serialized by said platforms, and sent across the wire as needed.
And it’s incredibly easy to implement this in PHP. You just need to make sure your class implements the JsonSerializable interface.
From the documentation, the interface does the following:
Objects implementing JsonSerializable can customize their JSON representation when encoded with json_encode().
The only method a class needs to provide is jsonSerialize, and though it’s likely you will want to serialize all of the properties of an object (as well as its state whenever its called), you can customize the implementation however you’d like.