PHP
  Home arrow PHP arrow Page 3 - User-defined Interfaces in PHP 5: Introduction to Core Concepts
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? 
PHP

User-defined Interfaces in PHP 5: Introduction to Core Concepts
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2005-12-19


    Table of Contents:
  • User-defined Interfaces in PHP 5: Introduction to Core Concepts
  • What are interfaces? Defining core concepts
  • The practical side: defining the “DeSerializer interface and “PostSaver” class
  • Making the Round Trip: defining the “MySQLCache” class
  • A functional example: using the “MySQLCache” and “PostSaver” classes

  • 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


    User-defined Interfaces in PHP 5: Introduction to Core Concepts - The practical side: defining the “DeSerializer interface and “PostSaver” class
    ( Page 3 of 5 )

    In order to get a pretty clear idea of user-defined interfaces, I’ll show two concrete classes that implement the same interface. The first one is a simple POST data saver class, which saves and retrieves sequentially data coming from POST forms. The second one consists of a caching class that saves a MySQL query resource in a cache file, and reads data either from the server or the cache file. The caching system is controlled by a time expiry cache trigger.

    Despite the fact that both classes neither maintain a close relationship nor belong to the same family type, they’ll implement the same interface, so the two classes will be “bridged” through what I call a “DeSerializer” interface.

    The purpose of the “DeSerializer” interface is to provide two abstract (and of course unimplemented) methods, “getSerializedData()” and “getDeserializedData()”, to be explicitly defined within the previous classes. As you’ll see in a moment, each class will expose these methods, even when they don’t create the same type of objects.

    To begin, here is the definition of the “DeSerializer” interface:

    // interface DeSerializer
    // defines generic methods serializeData() - unserializeData()
    interface DeSerializer{
        public abstract function getSerializedData();
        public abstract function getUnserializedData();
    }

    With reference to the above example, I’ve defined the interface simply by prefixing its name with the “interface” keyword. Then I’ve declared the two abstract methods “getSerializedData()” and “getUnserializedData()”, as mentioned previously.

    From this point onward, each possible class that implements this interface must provide a specific definition for the methods, which implies that many classes can use the same methods, implemented in a different way.

    Having defined the interface, the next step is to declare the two respective classes. According to this, below is the definition for the “PostSaver” class:

    // class PostSaver
    class PostSaver implements DeSerializer{
        private $postdata; // post data
        private $postdataFile; // file to save post data
        // constructor
        public function __construct($postdataFile='defaultFile.txt'){
            $this->postdata=$_POST;
            $this->postdataFile=$postdataFile;
        }
        // save post data to file
        public function writePostData(){
            // open or create data file
            if(!$fp=fopen($this->postdataFile,'w')){
                throw new Exception('Error opening data file');
            }
            // save serialized post data
            if(!fwrite($fp,$this->getSerializedData())){
                throw new Exception('Error writing to data file');
            }
            fclose($fp);
        }
        // read post data from file
        public function readPostData(){
            if(!$this->postdata=file_get_contents($this->postdataFile)){
                throw new Exception('Error reading data file');
            }
            // return unserialized post data
            return $this->getUnserializedData();
        }
        // serialize post data
        public function getSerializedData(){
            return serialize($this->postdata);
        }
        // unserialize post data
        public function getUnserializedData(){
            return unserialize($this->postdata);
        }
    }

    As you can see, the “PostSaver” class implements the “DeSerializer” interface, and its functionality is rather simple. The class obtains an array of data from a post form (initialized through the constructor), then serializes the post array and finally writes the obtained string to a given text file. This task is performed by the “writePostData()” method.

    Similarly, post data is retrieved through the “readPostData()” method, which unserializes the data stored in the text file and returns the post array. Of course, the point worth mentioning here is the explicit definition of the “getSerializedData()” and “getUnserializedData()” methods within the class, which are listed below:

    // serialize post data
    public function getSerializedData(){
        return serialize($this->postdata);
    }

    // unserialize post data
    public function getUnserializedData(){
        return unserialize($this->postdata);
    }

    Now I guess you have a pretty clear idea of the usage of interfaces. The generic functionality defined by the interface is specifically implemented within the class.

    With the first class already analyzed, the next step consists of defining the second caching class, “MySQLCache”, to demonstrate how it also implements the “DeSerializer” interface. So, keep reading to find out how this is done.



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

       

    PHP ARTICLES

    - 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
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT