PHP
  Home arrow PHP arrow Page 5 - Abstract Classes in PHP: Setting Up a Concrete Example
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

Abstract Classes in PHP: Setting Up a Concrete Example
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 15
    2006-02-01


    Table of Contents:
  • Abstract Classes in PHP: Setting Up a Concrete Example
  • Setting up a concrete example: Defining the hierarchy of classes
  • Deriving subclasses from the parent abstract class: defining the “resultProcessor” class
  • More subclasses ahead: defining the “fileProcessor” class
  • Assembling the pieces: putting the classes to work together

  • 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


    Abstract Classes in PHP: Setting Up a Concrete Example - Assembling the pieces: putting the classes to work together
    ( Page 5 of 5 )

    As I said before, let’s first list the sample “dataProcessor” abstract class and its corresponding subclasses, and then instantiate some objects and use some of their methods. Here are all the sample classes you learned previously:

    // define base abstract class
    class dataProcessor{
     function dataProcessor(){
      if(get_class($this)=='dataProcessor'||!is_subclass_of($this)){
               trigger_error('This class is abstract.It cannot be
    instantiated!',E_USER_ERROR);
              }
     }
     function toString(){}
     function toArray(){}
     function toXML(){}
    }
    // derive 'resultProcessor' class from 'dataProcessor'
    class resultProcessor extends dataProcessor{
     var $result;
     function resultProcessor($result){
      if(get_resource_type($result)!='mysql result'){
       trigger_error('Invalid MySQL result',E_USER_ERROR);
       exit();
      }
      $this->result=$result;
     }
     // returns database table data as string
     function toString(){
      $data='';
      while($row=mysql_fetch_row($this->result)){
       foreach($row as $col){
        $data.=$col;
       }
       $data.="\n";
      }
      return $data;
     }
     // returns database table data as array
     function toArray(){
      $data=array();
      while($row=mysql_fetch_row($this->result)){
       $data[]=$row;
      }
      return $data;
     }
     // returns database table data as XML
     function toXML(){
      $xml='<?xml version="1.0" encoding="iso-8859-1"?>'."\n";
      $xml.='<tabledata>'."\n";
      $data=$this->toArray();
      foreach($data as $row=>$value){
       foreach($value as $field){
        $xml.='<fieldnode>'.$field.'</fieldnode>'."\n";
       }
      }
      $xml.='</tabledata>';
      return $xml;
     }
    }
    // derivate 'fileProcessor' class from 'dataProcessor'
    class fileProcessor extends dataProcessor{
     var $file;
     function fileProcessor($file){
      if(!file_exists($file)){
       trigger_error('Invalid file!',E_USER_ERROR);
       exit();
      }
      $this->file=$file;
     }
     // returns filedata as string with <br /> tags
     function toString(){
      return nl2br(file_get_contents($this->file));
     }
     // returns file data as array
     function toArray(){
      return file($this->file);
     }
     // returns file data as XML
     function toXML(){
      $xml='<?xml version="1.0" encoding="iso-8859-1"?>'."\n";
      $xml.='<filedata>'."\n";
      $filedata=$this->toArray();
      foreach($filedata as $row){
       $xml.='<filenode>'.trim($row).'</filenode>'."\n";
      }
      $xml.='</filedata>';
      return $xml;
     }
    }

    Having listed all the classes you learned before, I’ll create a simple text file, “books.txt”, which is populated with data about a few programming books:

    PHP and MySQL Web Development - Luke Welling and Laura Thompson
    JavaScript Learning Guide - Tom Negrino and Dori Smith
    Java How to program - Deitel and Deitel

    Now, see what happens when I spawn a “fileProcessor” object and call its methods:

    // instantiate 'fileProcessor' object
    $fproc=&new fileProcessor(books.txt');
    // display data as string
    echo $fproc->toString();

    The above scripts outputs the following source code:

    PHP and MySQL Web Development - Luke Welling and Laura Thompson<br />
    JavaScript Learning Guide - Tom Negrino and Dori Smith<br />
    Java How to program - Deitel and Deitel

    Next, I’ll use the “toArray()” method, as follows:
    echo $fproc->toArray();
    And the output is the following:
    Array

    Finally, take a look at the corresponding output, when I invoke the “toXML()” method:

    header('Content-Type: text/xml');
    echo $fproc->toXML();

    <?xml version="1.0" encoding="iso-8859-1" ?>
    <filedata>
    <filenode>PHP and MySQL Web Development - Luke Welling and Laura
    Thompson</filenode>
    <filenode>JavaScript Learning Guide - Tom Negrino and Dori
    Smith</filenode>
    <filenode>Java How to program - Deitel and Deitel</filenode>
    </filedata>

    Although the above code samples look really simple, they allow me to demonstrate how all the inherited methods implement a concrete functionality within the respective child classes.

    Additionally, coming to the “resultProcessor” class, below there are some examples that show the values returned by the different methods, after inserting some records into a sample “movies” database table:

    // include MySQL class file
    require_once 'mysqlclass.php';
    // connect to MySQL
    $db=&new MySQL(array('host'=>'host','user'=>'user','password'=>'password',
    'database'=>'database'));
    // create $result object
    $result=$db->query("SELECT * FROM movies");
    // instantiate 'resultProcessor' object & get MySQL result set
    $resProc=&new resultProcessor($result->getQueryResource());

    // display dataset as string
    echo $resProc->toString();

    1 The Shinning Jack Nicholson 2 Carrie Sissy Spacek 3 Misery Kathy Bates

    // get dataset as array
    echo $resProc->toArray();

    Array

    //get dataset as XML
    header('Content-Type: text/xml');
    echo $resProc->toXML();

    <?xml version="1.0" encoding="iso-8859-1" ?>
    <tabledata>
    <fieldnode>1</fieldnode>
    <fieldnode>The Shinning</fieldnode>
    <fieldnode>Jack Nicholson</fieldnode>
    <fieldnode>2</fieldnode>
    <fieldnode>Carrie</fieldnode>
    <fieldnode>Sissy Spacek</fieldnode>
    <fieldnode>3</fieldnode>
    <fieldnode>Misery</fieldnode>
    <fieldnode>Kathy Bathes</fieldnode>
    </tabledata>

    As you can see, I’ve provided you with some instructive examples which demonstrate a correct implementation of an abstract class in PHP 4, after deriving a couple of child classes which are responsible for processing file data, as well as MySQL result sets. As usual, feel free to study the sample codes and use them to start writing your own abstract classes.

    Closing Time

    We’re finished, at least for the moment. In this second part of this series, I hope you learned how to implement an abstract, highly generic class, by creating a base class on top of the corresponding hierarchy, and next deriving a couple of subclasses, which provide concrete definitions for each inherited method.

    Over the final tutorial, I’ll explain by copious hands-on examples how to use abstract classes in PHP 5, along with their strong relationship with members visibility. So, see you in the last article!



     
     
    >>> 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 4 Hosted by Hostway
    Stay green...Green IT