The __sleep() magic method is mainly responsible of customizing the data collection while serialization of a class.
Let’s first look at a simple example on how to serialize & unserialize a class in PHP
Serialize a class
class DevPeel
{
public $name = 'devpeel';
}
$class = new DevPeel();
var_dump(serialize($class));
Now let’s take the serialized string and try to unserialize it.
Unserialize a class
$serialized = 'O:7:"DevPeel":1:{s:4:"name";s:7:"devpeel";}';
$class = unserialize($serialized);
var_dump($class);
and the output:
object(__PHP_Incomplete_Class)#1 (2) {
["__PHP_Incomplete_Class_Name"]=>
string(7) "DevPeel"
["name"]=>
string(7) "devpeel"
}
Another Example (Job Dispatch)
Let’s see a simple example of serializing data of a job assigned to email user something. We’ll first serialize the data and later try to unserialize it.
class SendUserEmail
{
protected $user;
public function __construct(User $user){
$this->user = $user;
}
public function handle(){
var_dump('send email');
}
}
class User
{
protected $data =[
'email'=>'[email protected]'
];
public function __sleep(){
return ['data'];
}
}
$user = new User();
$job = new SendUserEmail($user);
$string = serialize($job);
var_dump($string);
& the output:
string(111) "O:13:"SendUserEmail":1:{s:7:"*user";O:4:"User":1:{s:7:"*data";a:1:{s:5:"email";s:17:"[email protected]";}}}"
If required to put this into our database, we probably need to base64_encode
this string.
Now let’s convert it back using unserialize helper function, likeso
$unserialized = unserialize(base64_decode($string));
& the unserialized output:
object(SendUserEmail)#3 (1) {
["user":protected]=>
object(User)#4 (1) {
["data":protected]=>
array(1) {
["email"]=>
string(17) "[email protected]"
}
}
}
Now after unserialzing, we can still access to methods of the class likeso,
$unserialized->handle();
It will run the handle()
method inside of SendUserEmail
class & we can carry out further processes.