Home arrow PHP arrow Page 2 - PHP Datastorage Class

Top of the Page - PHP

Many websites use databases for storing data for use by web applications. There are situations in which this is not the best solution, however. For light, moderate, or temporary storage requirements, you might prefer to use flat files, session variables, and cookies. This article will describe how to create a class that handle all of these. It is the first of two parts.

TABLE OF CONTENTS:
  1. PHP Datastorage Class
  2. Top of the Page
  3. Flat Files
  4. Getting Data In
  5. Getting Data Out
By: Chris Root
Rating: starstarstarstarstar / 10
November 14, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

This is a PHP class. As such it resides in its own file and is used by including it in your application documents. If you are using it with session variables you will need to use the session_start() function first for each page it is included in.

<?php
session_start();
require("datastore.php");
$items = new datastore("s","cart");
?>

One thing to note before we dig into the code of this class. If you use the cookie functionality, you will need to be aware of a few things.

First of all, the cookie-related code in this example is included for demonstration purposes only. Unlike the rest of the code in this class, the cookie code has not been extensively tested. It does however live happily in the code without interfering with any other operations.

Another thing to remember is that, when setting cookies, you must not have any whitespace before the line of code that sets it, and you definitely cannot have any other output to the browser preceding the setting of a cookie.

Finally, if you plan to use cookies with recent versions of Internet Explorer you might want to read up on something called P3P if you haven't already. Otherwise it's likely your cookies will never get saved.

The Internals

The first part of the class is the declaration.

class datastore
{
    //code
}

Everything in the class resides in between the curly braces.

Next we declare a few variables. If you are used to JavaScript you may recognize the keyword "var". This is the only place in PHP where it is used.

    var $self = "";
    var $data_dir = "";
    var $items = null;
    var $dataname = "datastore";
    var $edited = false;
    var $datafile = null;
    var $error = "";
    var $mode = "";

These variables need not be assigned values at this point, but as matter of style I usually do.

The next step is a constructor function. In PHP classes a constructor function is usually named the same as the class (prior to PHP 5 this was required). The purpose of the constructor is to initialize a newly created object based on the class. Variables can be set and internal methods called to tailor that instance to a particular situation. The code for the datastore constructor is below.

function datastore($mode="s",$name="",$dir="")
{
     $this->self = dirname(__FILE__);
     strtolower($mode);
     $this->mode = $mode;
     if($name != "")
     {
           $this->dataname = $name;
     }
     if($mode == "s")
     {
           if(isset($_SESSION[$this->dataname]))
           {
                $this->items = unserialize($_SESSION[$this->dataname]);
           }
           else
           {
                $_SESSION[$this->dataname] = "";;
           }
     }
     else if($mode == "f")
     {
           if($dir == "")
           {
                $this->data_dir = $this->self."/data";
           }
           else
           {
                $this->data_dir = $this->self."/".$dir;
           }
           if(!is_dir($this->data_dir))
           {
                if(!mkdir($this->data_dir))
                {
                     $this->err("Trouble making directory",1);
                }
           }
           if(!file_exists($this->data_dir.$this->dataname.".dta"))
           {
                if(!$this->datafile = fopen($this->data_dir.$this->dataname.".dta","w"))
                {
                     $this->err("Problem Creating Datafile",1);/**/
                }
                else
                {
                     fclose($this->datafile);
                }
           }
           else
           {
                if(!$datastr = file_get_contents($this->data_dir.$this->dataname.".dta"))
                {
                     $this->err("Problem Opening Datafile",1);
                }
                else
                {
                     $this->items = unserialize($datastr);
                }
           }
     }
}

When an instance of the datastore is created we use arguments to the constructor to decide where we are going to store the data and what we will label the container. In order to make the arguments optional and provide a default value for each we use the syntax $mode="s" in the parenthesis.

The first of these arguments is the mode. A value of "s" will set a session variable for storage of our information. Using a value of "f" will use a flat file and "c", as anyone who has watched Sesame Street will know, stands for "cookie". The default is to use a session variable.

$this->self = dirname(__FILE__);
strtolower($mode);
$this->mode = $mode;
if($name != "")
{
     $this->dataname = $name;
}

We first establish the real location of the class file using the magic constant "__FILE__" (more on this in a moment). Then we ensure that the mode is lowercase, and that an instance variable is set to establish the storage mode we are using. The "name" argument will set the name of the data container. The default for this property is "datastore". The flat file, session variable or cookie will be named accordingly. The next step is to handle the mode of storage.

if($mode == "s")
{
     if(isset($_SESSION[$this->dataname]))
     {
           $this->items = unserialize($_SESSION[$this->dataname]);
     }
     else
     {
           $_SESSION[$this->dataname] = "";
     }
}

The first mode to tackle is the session variable. If the appropriately named session variable exists, the object's "items" property is set. This class stores and retrieves data using the serialize and unserialize functions. Serializing the data, especially when using flat files, allows the storage of complex data structures and even objects in an easily retrievable format, allowing them to retain their original structure. In this case, if the session variable we are looking for is there, we use the unserialize function to put the data into "items".

The datastore class uses a very simple data structure that resembles a table with rows of records and fields of data in a database. A master associative array (items) can be considered the table. Within each labeled element of the array is another associative array that is much like a row in a database. Each of these arrays have elements or fields that have a key (field name) and value. The key for each row of data is the key for that array.

If the session variable is not present it is created.



 
 
>>> More PHP Articles          >>> More By Chris Root
 

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: