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!

Advantages of Hiring PHP Developer for your Website Project

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...

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 to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

Hire PHP Developer and Web Developer for your Online Business

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...

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 development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company