Serialize and Unserialize objects in PHP for Data Transfer Objects (DTOs)

December 16th 2012

Sometimes, in PHP it's necessary to store a string representation of an object for a short while. One such example is when you need to transport an object to another server via a RESTful interface.

For these situations I like to use a very simple DTO of the item.

Take this class for example:

PHP Code:
<?php
class Simple_Dto {

    
/**
     * @var string
     */
    
public $name;

    
/**
     * @var integer
     */
    
public $age;

    
/**
     * @var string
     */
    
public $city;

    public function 
__construct() {

    }

    
/**
     * @return the $name
     */
    
public function getName ()
    {
        return 
$this->name;
    }

    
/**
     * @return the $age
     */
    
public function getAge ()
    {
        return 
$this->age;
    }

    
/**
     * @return the $city
     */
    
public function getCity ()
    {
        return 
$this->city;
    }

    
/**
     * @param string $name
     */
    
public function setName ($name)
    {
        
$this->name $name;
    }

    
/**
     * @param mixed:string:integer $age
     */
    
public function setAge ($age)
    {
        
$this->age $age;
    }

    
/**
     * @param string $city
     */
    
public function setCity ($city)
    {
        
$this->city $city;
    }

}

First, set the object up using this:

PHP Code:
<?php
$dto 
= new Simple_Dto();
$dto->setAge(32);
$dto->setName("Joe");
$dto->setCity("London");

Now, the value of this object is below:

PHP Code:
<?php
var_dump
($dto);
/**
    object(Simple_Dto)#1 (3) {
      ["name"]=>
      string(3) "Joe"
      ["age"]=>
      int(32)
      ["city"]=>
      string(6) "London"
    }
 */

To store this object call:

PHP Code:
<?php
$serialized 
serialize($dto);

This gives you a string like below:

PHP Code:
<?php
var_dump
($serialized);
/**
string(82) "O:10:"Simple_Dto":3:{s:4:"name";s:3:"Joe";s:3:"age";i:32;s:4:"city";s:6:"London";}"
 */

Now, to retrieve the object again all we have to do is call:

PHP Code:
<?php
$unserialised 
unserialize('O:10:"Simple_Dto":3:{s:4:"name";s:3:"Joe";s:3:"age";i:32;s:4:"city";s:6:"London";}');
var_dump($unserialised);
/**
    object(Simple_Dto)#2 (3) {
      ["name"]=>
      string(3) "Joe"
      ["age"]=>
      int(32)
      ["city"]=>
      string(6) "London"
    }
 */

Using this makes it incredibly easy to manage objects back and forth between systems and RESTful interfaces. This is only a short example (without any validation checks!)