Page 1 of 1

Serialization in PHP How to create storable representations of objects. Rate Topic: ****- 1 Votes

#1 joeyadms  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 41
  • View blog
  • Posts: 178
  • Joined: 04-May 08

Posted 09 June 2008 - 01:38 AM

Serialization in PHP

What is serialization?
PHP code is static, however values and structures loaded during runtime are dynamic and are lost
after execution.

Using serialization, we are able to create a storable representation of the current state
of a value, wether it be an array, scalar, or even objects!

WHY? Can't you just store the values?
Of course you can store just the values, however values do not maintain links and relationships.

Say for instance, a user authenticates with your site and does some surfing, it is possible to save
that session data by serializing it and storing it in a database. That way when they return, they can
pick up where they left off. This is an easy way of keeping details on users without huge database tables
and complex queries.

What I really LOVE about serialization, is the ability to store objects. This means you can create
a very powerful class and methods, that maybe calculate statistic data, or hold records. We can
then save the objects current state, and then restore it on the next request to continue to compute data.


A Quick Note on Objects!
Even though you serialize an object, you must still have the class/classes the object uses included in your script.

What Can I serialize?
Anything, more practically, something that holds information other than scalar data, such as arrays and objects will be
prime for serialization.



Show Me Some Code!
serialization works by two functions, serialize() and unserialize(), which do exactly
what they sound like.


Here are some examples.

shop.class.php
class shop {
 public hot_item;
 public function changeItem($itemName){
   $this->hot_item = $itemName;
 }
}



Page1.php
include('shop.class.php');

$shop = new shop();
$shop->changeItem('boots');
$s = serialize($shop);
$fp = fopen("store", "w");
fwrite($fp, $s);
fclose($fp);



Page2.php
include('shop.class.php');

$serData = implode("", @file("store"));
$shop = unserialize($serData);
echo $shop->hot_item;


This would output boots .

So you see it is very easy to understand and implement, and is practical and power om real world situations.

For example, on a small scale you can mimick a database, or a registry, without needing an actual database system to
query, see below.


Be careful, serialized data can become big if you store enough things, but on a small scale, or individual serialization and
storing will prove just fine.

Example of Employee Registry
employee.class.php
class employees {

// File to save data to
public $save_file = "save";

// File to log errors to
public $error_file = "error";

// Log Errors to file
public $log_errors = 1;

// Display Errors
public $display_errors = 1;


// Holds employee data
public $employee_list = array();

public function save(){
  $s = serialize($this);
  if($fp = fopen($this->save_file, "w")){
	  if(fwrite($fp, $s) === FALSE){
		 $error = "Could not write to ($this->savefile)";
		 $this->error($error);
	   }
	  fclose($fp);
  } else {
	$error = "Could not open file ($this->saveFile)";
	$this->error($error);
  }
}

public function restore(){
  $s =  implode("", @file($this->save_file));
  return unserialize($s);
}

public function error($errorStr){
  if($this->log_errors){
	$fp = fopen($this->error_file,'a');
	fwrite($fp,$errorStr);
	fclose($fp);
  }
  if($this->display_errors){
	die($errorStr);
  }
}

function addEmployee($data){
  $this->employee_list[] = $data;
}

function getById($id){
  return $this->get(array('key' => 'id', 'val' => $id));
}

function getByName($name){
 return $this->get(array('key' => 'name', 'val' => $name);
}

function get($data){
  $key = $data['key'];
  $val = $data['val'];
  foreach($this->employee_list as $e_data) {
	if($e_data[$key] == $val){
	  return $e_data;
	}
  }
}

}



This example is hacked together, but you get the idea, you could do this

One day
include('employee.class.php');
$e = new employees();
$e->addEmployee('id' => 1, 'name' => 'Joey');
$e->save();



Another Day
include('employee.class.php');
$e = employees::restore();
$j = $e->getById(1);
echo $j['name'];



Well I hope that helps you understand serialization in PHP, so go, open your minds and imagination, and create something
incredible.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1