Home arrow PHP arrow Page 2 - Persistent Objects and Different Session Variables in PHP 5

Building a basic persistent class in PHP 5 - PHP

Despite its rather intimidating name, persistent objects represent a pretty simple concept applied very often in software development. It's aimed at creating structured entities that can maintain their status across different stages of an application. This six-part series will take the mystery out of persistent objects so you can use them in your own applications.

TABLE OF CONTENTS:
  1. Persistent Objects and Different Session Variables in PHP 5
  2. Building a basic persistent class in PHP 5
  3. Saving class instances to different session variables
  4. Building a wrapping example
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
September 21, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Before I begin demonstrating how to make the persistent class defined in the previous article slightly more flexible, first Iíd like to summarize how to use it in its current state. This way, you'll see how an instance of it can be saved to a specific predefined variable, and at later time, restored on a different web page.

So here is the complete definition of the persistent class. I decided to call it ďUser,Ē since it's useful for storing data on a fictional user. Have a look at it:

class User

{

private $data = array();

 

// constructor (not implemented)

public function __construct(){}

 

// factory method

public static function factory()

{

session_start();

if(isset($_SESSION['user']) === TRUE)

{

return unserialize($_SESSION['user']);

}

return new User();

}

 

// set undeclared property

public function __set($property, $value)

{

$this->data[$property] = $value;

}

 

// get undeclared property

public function __get($property)

{

if (isset($this->data[$property]) === TRUE)

{

return $this->data[$property];

}

}

 

// save object to session variable

public function __destruct()

{

$_SESSION['user'] = serialize($this);

}

}

Well, to be frank, understanding how an instance of the previous ďUserĒ class can persist across different HTTP requests isnít rocket science. As you can see, the class restores (or creates) a user object via its ďfactory()Ē method, while its destructor takes care of storing the corresponding instance to a statically-assigned session variable, called ď$_SESSION['user']. Itís really that simple.

Now that you remember how the previous ďUserĒ class was defined originally, itís time to demonstrate its actual functionality. To do that, Iím going to spawn an object from it, which will store some data about me on the specified session variable (and donít think that Iím being too egocentric, since itís only for example purposes).

The code fragment that performs this task is the following:

// example on creating a persistent object

$user = User::factory();

$user->fname = 'Alejandro';

$user->lname = 'Gervasio';

$user->email = 'alejandro@mydomain.com';

Behind this short script, a few interesting things are happening. First, it creates a new user object by way of the static ďfactory()Ē method, and then it uses property overloading to assign dynamically some values to three undeclared properties. Finally, it saves the object to the $_SESSION['user'] variable via the classís destructor.

Of course, itís also possible to create persistent objects in a more conventional way, without using some of the magic methods offered by PHP 5, but I decided to code the ďUserĒ class like this to make it a bit more compact.

Now, returning to the previous code sample, once the user object has been saved to the specified session variable, itís necessary to show how it can be restored and modified on a different web page. To achieve this, the page in question should look similar to this:

<?php

 

class User

{

private $data = array();

 

// constructor (not implemented)

public function __construct(){}

 

// factory method

public static function factory()

{

session_start();

if(isset($_SESSION['user']) === TRUE)

{

return unserialize($_SESSION['user']);

}

return new User();

}

 

// set undeclared property

public function __set($property, $value)

{

$this->data[$property] = $value;

}

 

// get undeclared property

public function __get($property)

{

if (isset($this->data[$property]) === TRUE)

{

return $this->data[$property];

}

}

 

// save object to session variable

public function __destruct()

{

$_SESSION['user'] = serialize($this);

 

}

}

 

// assign new properties to the persistent object

$user = User::factory();

$user->fname = 'John';

$user->lname = 'Doe';

$user->email = 'john@domain.com';

 

?>

From the above example, itís clear to see how easy it is to retrieve the persistent object created previously on a different web page, as well as to assign new values to its properties. In this particular case, I decided to modify those properties, but naturally itís possible to load the object via its ďfactory()Ē method and keep its internal state untouched. That was really simple to do, wasnít it?

So far, so good. At this stage, I showed you how to create and use an object thatís capable of maintaining its status through two different web pages by using only a single session variable. However, as I said in the introduction, the objectís originating class in its current state is pretty inflexible, since it stores the pertinent instance on a predefined variable that canít be inputted from the outside.

In reality, itíd be useful to provide the class with the ability to store its instances on different session variables, other than the predetermined $_SESSION['user'] that you saw before. Therefore, in the section to come Iím going to modify slightly the definition of the sample ďUserĒ class, so it can expose the aforementioned capability.

Now, read the following segment. Itís only one click away.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: