PHP
  Home arrow PHP arrow Page 2 - PHP Datastorage Class
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

PHP Datastorage Class
By: Chris Root
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 10
    2005-11-14


    Table of Contents:
  • PHP Datastorage Class
  • Top of the Page
  • Flat Files
  • Getting Data In
  • Getting Data Out

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    PHP Datastorage Class - Top of the Page
    ( Page 2 of 5 )

    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
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek