Welcome to Dream.In.Code
Getting Help is Easy!

Join 132,474 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,359 people online right now. Registration is fast and FREE... Join Now!




Serialization in PHP

 
Reply to this topicStart new topic

> Serialization in PHP, How to create storable representations of objects.

joeyadms
Group Icon



post 9 Jun, 2008 - 12:38 AM
Post #1


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
CODE

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


Page1.php
CODE

include('shop.class.php');

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


Page2.php
CODE

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
CODE

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
CODE

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


Another Day
CODE

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.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 11/22/08 02:29PM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month