PHP
  Home arrow PHP arrow Page 4 - Enforcing Object Types in PHP: Filtering Input Objects in PHP 4
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

Enforcing Object Types in PHP: Filtering Input Objects in PHP 4
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 6
    2006-02-15


    Table of Contents:
  • Enforcing Object Types in PHP: Filtering Input Objects in PHP 4
  • Enforcing object types in PHP 4: building (X)HTML widgets classes
  • Building an object-base web page: unexpected results due to the lack of object type checking
  • Preventing code contamination: enforcing object types inside of 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


    Enforcing Object Types in PHP: Filtering Input Objects in PHP 4 - Preventing code contamination: enforcing object types inside of classes
    ( Page 4 of 4 )

    Fortunately, filtering input objects is fairly simple. One of the easiest ways to check whether an object is an instance of a specific class is by using the “is_a()” PHP built-in function. As you probably know, this function checks to see if a particular object is an instance of a given class or subclass, so it is very convenient to use for verifying object types.

    Notice that in the previous sentence I used the words “instance of.” This follows a certain logic. The “is_a()” function has been deprecated in PHP 5 in favor of the “instanceof” operator, which is very useful for checking what object types you’re working with, in addition to determining whether objects are implementers of a particular interface. However, this is the subject of a future article, so now let’s focus again on the “is_a()” function.

    As I said previously, I’ll introduce object type checking inside the page generator class, by using the “is_a()” function I discussed before, in order to avoid having objects of the incorrect type being utilized within this class. Please look at the code below:

    class PageGenerator{
        var $output='';
        var $title;
        function PageGenerator($title='Default Page'){
            $this->title=$title;
        }
        function doHeader(){
            $this->output='<html><head><title>'.$this-
    >title.'</title></head><body>';
        }
                // force type of input objects
        function addHTMLElement($htmlElement){
            if(!is_a($htmlElement,'HTMLElement')){
                trigger_error('Invalid (X)HTML
    element',E_USER_ERROR);
            }
            $this->output.=$htmlElement->getHTML();
        }
        function doFooter(){
            $this->output.='</body></html>';
        }
        function fetchHTML(){
            return $this->output;
        }
    }

    As the above class shows, its “addHTMLElement()” method now is capable of determining the type of objects passed as a parameter, by the “is_a()” function. In this example, if input objects aren’t of the type “HTMLElement”, the class will trigger a fatal error and the script will be stopped. As you can see, a minor change in the class code can be translated into a major improvement of the logic implemented by the class.

    Now that the web page generator class is enforcing the type of input objects, it’s also possible to go one step up to the implementation of object type checking inside the proper (X)HTML widget classes. Perhaps you’re wondering: what’s the point of doing that? Well, this process would allow the construction of more complex web pages by nesting their building elements, along with the achievement of much more than simple web page layouts.

    All I have to do is refactor the “getHTML()” method of all the (X)HTML widget classes, and check whether the corresponding input data is also another (X)HTML widget object. After introducing this modification, this is how the (X)HTML widgets classes now look:

    class Div extends HTMLElement{
        var $output='<div ';
        var $data;
        function Div($attributes=array(),$data){
            parent::HTMLElement($attributes);
            if(!is_a($data,'HTMLElement')&&!is_string($data)){
                trigger_error('Invalid type for data
    parameter',E_USER_ERROR);
            }
            $this->data=$data;
        }
        // concrete implementation for 'getHTML()' method
        function getHTML(){
            foreach($this->attributes as $attribute=>$value){
                $this->output.=$attribute.'="'.$value.'" ';
            }
            $this->output=substr_replace($this->output,'>',-1);
            $this->output.=(is_a($this->data,'HTMLElement'))?$this-
    >data->getHTML():$this->data;
            $this->output.='</div>';
            return $this->output;
        }
    }
    class Header1 extends HTMLElement{
        var $output='<h1 ';
        var $data;
        function Header1($attributes=array(),$data){
            parent::HTMLElement($attributes);
            if(!is_a($data,'HTMLElement')&&!is_string($data)){
                trigger_error('Invalid type for data
    parameter',E_USER_ERROR);
            }
            $this->data=$data;
        }
        // concrete implementation for 'getHTML()' method
        function getHTML(){
            foreach($this->attributes as $attribute=>$value){
                $this->output.=$attribute.'="'.$value.'" ';
            }
            $this->output=substr_replace($this->output,'>',-1);
            $this->output.=(is_a($this->data,'HTMLElement'))?$this-
    >data->getHTML():$this->data;
            $this->output.='</h1>';
            return $this->output;
        }
    }
    class Paragraph extends HTMLElement{
        var $output='<p ';
        var $data;
        function Paragraph($attributes=array(),$data){
            parent::HTMLElement($attributes);
            if(!is_a($data,'HTMLElement')&&!is_string($data)){
                trigger_error('Invalid type for data
    parameter',E_USER_ERROR);
            }
            $this->data=$data;
        }
        // concrete implementation for 'getHTML()' method
        function getHTML(){
            foreach($this->attributes as $attribute=>$value){
                $this->output.=$attribute.'="'.$value.'" ';
            }
            $this->output=substr_replace($this->output,'>',-1);
            $this->output.=(is_a($this->data,'HTMLElement'))?$this-
    >data->getHTML():$this->data;
            $this->output.='</p>';
            return $this->output;
        }
    }
    class UnorderedList extends HTMLElement{
        var $output='<ul ';
        var $items=array();
        function UnorderedList($attributes=array(),$items=array()){
            parent::HTMLElement($attributes);
            if(!is_array($items)){
                trigger_error('Invalid parameter for list
    items',E_USER_ERROR);
            }
            $this->items=$items;
        }
        // concrete implementation for 'getHTML()' method
        function getHTML(){
            foreach($this->attributes as $attribute=>$value){
                $this->output.=$attribute.'="'.$value.'" ';
            }
            $this->output=substr_replace($this->output,'>',-1);
            foreach($this->items as $item){
                $this->output.=(is_a($this->data,'HTMLElement'))?
    $this->data->getHTML():$this->data;
            }
            $this->output.='</ul>';
            return $this->output;
        }
    }

    As illustrated above, all the (X)HTML widget classes are now capable of rendering nested page elements. The checking line below:

    $this->output.=(is_a($this->data,'HTMLElement'))?$this->data-
    >getHTML():$this->data;

    first verifies whether the $this->data property is an object of type “HTMLElement”. If it is, then its corresponding “getHTML()” method is called up. Otherwise, data is appended as a regular string to the class’ overall output. Additionally, each class constructor (excepting the “UnorderedList” class) performs a check, in order to make sure that only strings and “HTMLElement” objects are passed to it. It's simple and efficient.

    My last example shows a simple script, which uses some of the improved classes for building a web page with nested elements. Here’s the corresponding PHP snippet:

    $par=&new Paragraph(array('name'=>'par1','class'=>'parclass'),'Content for Paragraph element goes here');
    // nest paragraph element with div element
    $div=&new Div(array('name'=>'div1','class'=>'divclass'),$par);
    $pageGen=&new PageGenerator();
    $pageGen->doHeader();
    // add 'HTMLElement' objects
    $pageGen->addHTMLElement($div);
    $pageGen->doFooter();
    // display web page
    echo $pageGen->fetchHTML();

    Fine, after including some lines of code within the sample classes, useful for enforcing a particular type of object, I ended up with a bunch of classes that build web pages, and also allow nesting page elements. After studying all the examples you just saw, forcing object types in PHP 4 isn’t hard work at all, right?

    Bottom line

    This is it for the moment. In this first tutorial, hopefully I provided you with some useful pointers for preventing your PHP 4 classes from being convoluted with input objects of the incorrect type. As you saw, enforcing object types is a very simple yet powerful concept, that definitely can be a true time saver when developing an object-based application.

    However, the topic is far from being completely covered. In the next article, I’ll be explaining the implementation of object type enforcement in PHP 5, by using the “instanceof” operator. In the meantime, have some fun programming with PHP, and most of all…don’t forget to check the input objects of your classes!



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

       

    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 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek