PHP: serializing an unserializing the simple way.

PHP: serializing an unserializing the simple way.

This is done automatically within PHP when you use the methods serialize($instance) and unserialize($string), by using the class instance, and the class string representation..

One of the tingly bits about saving the instance of a Class is serializing. For those who don’t know what the hell is this, the concept is very simple: you can represent an instance of a class as a string, so you can store anywhere, and then restore the instance from that same string.

This is done automatically within PHP when you use the methods serialize($instance) and unserialize($string), by using the class instance, and the class string representation, respectively:

$car = new Car(new OilEngine());
FileHandler::set('class.txt', serialize($car));
$sameCar = unserialize(FileHandler::get('class.txt'));

This is very useful to storing instances for later retrieval, like inside files, databases, in memory stores (like redis or memcached), or just anything that accepts text.

For example, saving a User class instance with its properties into a Session, so after this is retrieved in the next request we can restore the same User instance without having to pull it out from the Database. Hey, it just an example.

The old way of handling serialization

Before PHP 5.1, the only way to handle the serialization of classes was by using the methods __sleep() and __wakeup().

The first must return an array of properties that must be serialized, among other deep “cleaning”, before passing the instance to PHP’s default serialization process. The other would be called after the class is unserialized, which would allow you to modify the current instance to restore what has been lost.

Simple? Not by a long shot. Additionally, there are some caveats when using the default serialization:

  • The string is difficult to understand at first glance, since PHP uses a weird encoding to keep the Class shape.
  • You have to take into account that the properties of the class instance are also serializable or not, and have a work-around to restore them on unserialization.

As you can see, they seems counterproductive and confusing, but since PHP 5.1 there is no more need to take them into account since there is a much, much better way to handle serialization.

Welcome Serializable!

PHP has a handy interface called Serializable. This contains two methods you must set, called serialize() and unserialize(), and they replace the old calls without breaking backwards compatibility.

They’re pretty much self-explanatory, but in any case, here the gist:

  • serialize() is called when the class is being serialized. Its purpose is to pass an string representation of the Class to PHP. For example, we can just return a JSON-encoded list of attributes. The class name is appended automatically with the returned string— without the latter, PHP won’t know to which class to unserialize later.
  • unserialize() is called when the string is being unserialized to the corresponding Class. PHP will check the class name in the serialized string, pass the string to this method, and set whatever the class instance needs.

The unserialize() method is tricky to understand at first glance, but falter not. As the documentation says, this method acts like a “constructor”, meaning, the class will be instanced bypassing the _construct() method. If you need some dependencies set in the contruct(), the unserialize method will have to look for them manually, or (preferably) set them when the serialization is done:

$car = unserialize(FileHandler::get('class.txt'));
$car->setWheels(new Wheels());
$car->setPaintJob(new PaintJob('red'));


For setting the dependencies, a good way is to use setters on the unserialized class instance using the help of the ReflectionClass’s getConstructor() and the ReflectionMethod’s getParameters(), if you need something more advanced and modular.

But we’re getting ahead. Let’s serialize something.

Serializing and unserializing a Car

You wouldn’t download a Car? Not, still, but we can save it in a file. A simple glance on this “Car” class and you will note that it needs an Engine, we offer a PHP 7.4-style property to set the color, and it has serialization methods already set.

<?php

use Serializable;

class Car implements Serializable
{
    /**
     * The Car Engine
     *
     * @var \EngineInterface
     */
    protected EngineInterface $engine;

    /**
     * Color of the Car
     *
     * @var string
     */
    public string $color = 'white';

    /**
     * Car Constructor
     *
     * @return null
     */
    public function __construct(EngineInterface $engine)
    {
        $this-&gt;engine = $engine;
    }

    /**
     * If the Car has been turned on
     *
     * @var bool
     */
    public function itsOn()
    {
        return $this-&gt;engine-&gt;hasStarted();
    }

    /**
     * Set the Engine for this Car instance
     *
     * @param \EngineInterface $engine
     * @return void
     */
    public function setEngine(EngineInterface $engine)
    {
        $this-&gt;engine = $engine;
    }

    /**
     * Return the Engine used by this Car instance
     *
     * @return \EngineInterface
     **/
    public function getEngine()
    {
        return $this-&gt;engine;
    }

    /**
     * String representation of object
     *
     * @return string
     */
    public function serialize()
    {
        return json_encode([
            'engine' =&gt; get_class($this-&gt;engine),
            'engine_on' =&gt; $this-&gt;itsOn(),
            'color' =&gt; $this-&gt;color
        ]);
    }

    /**
     * Constructs the object
     *
     * @param string $serialized
     * @return void
     */
    public function unserialize($serialized)
    {
        $json = json_decode($serialized);

        $this-&gt;engine = new $json-&gt;engine();
        $this-&gt;color = $json-&gt;color;

        if ($json-&gt;engine_on) {
            $this-&gt;engine-&gt;turnOn();
        }
    }
}

When it serializes, it will do it as JSON. In that string, we will put the Engine class name, if the Engine it’s on, and the color.

When it unserializes, we will decode the JSON string. We will create a new Engine from the class name given, put the color, and start the engine if it was started.

Let’s check it in action.

<?php

use Car;
use Engines\OilEngine;
use Helpers\FileHandler;

$car = new Car(new OilEngine());
$car-&gt;color = red;

// 1
// Let's serialize the Car into a file using our File Handler static method. This
// will automatically set the content of the file using the serialization string.
FileHandler::set('car.txt', serialize($car));

// 2
// Now that it has been saved, we will check the contents of the file with the
// class instance. It should has been saved into the file as a JSON-esque string.
$contents = FileHandler::get('car.txt');

echo $contents;
// C:3:"Car":63:{{"engine":"Engines\\OilEngine","engine_on":false,"color":"red"}}

// 3
// Now we need to unserialize the Car class. We will call the unserialize() method
// so we can use the class as intenteded.
$sameCar = unserialize($contents);

// 4
// Finally, let's check if the engine is the "OilEngine" and the color is "red".
echo get_class($sameCar-&gt;getEngine());
// "Engines\\OilEngine";
echo $sameCar-&gt;color;
// "red"

// 5
// As a bonus line, we can change the Engine like in any other class;
$sameCar-&gt;setEngine(new PetrolEngine());

// The sky is the limit!

And voilà. No need to do weird sh*t in your code to save a Class instance. Hell, you could even save them into a USB stick and unserialize them in another computer. Technology!

Word of advice: you cannot serialize Closures, mainly because these have a context outside the Class. It’s like receiving a bill to pay but not knowing to whom.

Thanks for reading Originally published on https://itnext.io

If you liked this post, share it with all of your programming buddies!

php web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...