Enforcing Object Types in PHP: Filtering Input Objects in PHP 4

When you are writing an object-based web application in PHP, you want to prevent your classes from being convoluted with input objects of the incorrect type. These input objects can cause the application to throw a fatal error. In this article, you will learn how to enforce object types in PHP 4.

Introduction

During the development cycle of an object-based Web application, it’s a pretty common task to work with some PHP classes that accept other objects as part of their input parameters, whether they’re assigned as class properties for further use, or processed right at the moment of being passed in.

At first glance, this might seem like a hassle-free situation, and certainly there wouldn’t be a real need to worry about it. Nevertheless, reality can sometimes be quite different, a fact that can quickly break down a PHP application. In order to illustrate this, let me put you in the right context: you’re using a MySQL data processing class, which takes a query result object as its input argument for processing at a later time. As long as the correct type of object is passed into the processing class, everything is going to work just fine, but what if the class is fed with the wrong type of object?

I’m sure you can imagine the result: sooner or later, the application will fail in processing the object and throw a fatal error, causing the abrupt termination of program execution — not to mention a bunch of additional error messages that might be displayed, eventually, by the PHP parser. Moreover, if the application is being tested on a local server, the situation won’t go beyond the developer’s own frustration — but if it’s being run in a production environment, consequences might be much worse.

So, what’s the lesson of this story? Right, you guessed it. Obviously, the problem could be easily fixed by forcing the class in question to check the type of objects being passed in, so the class itself and the rest of the application code can’t be contaminated by objects of incorrect types. My conclusion about all this is that checking and enforcing object types in PHP is indeed an important topic that deserves an in-depth look, so in this series I’ll explore different approaches for verifying object types, either when programming with PHP 4 or PHP 5.

By the end of this series, hopefully you’ll have a clear idea of how to force object types inside of your PHP application, in this way avoiding further problems related to the so-called code contamination. Let’s get started.

{mospagebreak title=Enforcing object types in PHP 4: building (X)HTML widgets classes}

Culled from my own experience, I know that some topics are best understood by example, and that’s precisely the case when forcing object types in PHP 4. In order to demonstrate how you can filter input objects that eventually can mess up the beautifully-crafted code you wrote for your application, let me show you an example that can help you to understand the nature of the problem when objects of the wrong type are injected into client code.

First, I’ll define some useful (X)HTML widgets classes, aimed at rendering web page elements, and then create a web page generator class, which will accept these widgets for displaying the corresponding web document. My first example will begin with building a base “HTMLElement” class, and then continue by deriving some subclasses, all without including any object type checking routines, so you can see what happens when objects of an incorrect type are passed to this generator class.

Here are the (X)HTML widget classes I mentioned before:

// define base class ‘HTMLElement’
class HTMLElement{
    var $attributes;
    function HTMLElement($attributes){
        if(!is_array($attributes)){
            trigger_error(‘Invalid type for (X)HTML
attributes’,E_USER_ERROR);
        }
        $this->attributes=$attributes;
    }
    // abstract ‘getHTML()’ method
    function getHTML(){
        if(get_class($this)==’HTMLElement’||!is_subclass_of
($this,’HTMLElement’)){
            trigger_error(‘This method is abstract. It cannot be
called!’,E_USER_ERROR);
        }
    }
}
// define concrete class ‘Div’ – extends ‘HTMLElement’
class Div extends HTMLElement{
    var $output='<div ‘;
    var $data;
    function Div($attributes=array(),$data){
        parent::HTMLElement($attributes);
        $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.=$this->data.'</div>';
        return $this->output;
    }
}
// define concrete class ‘Header1′ – extends ‘HTMLElement’
class Header1 extends HTMLElement{
    var $output='<h1 ‘;
    var $data;
    function Header1($attributes=array(),$data){
        parent::HTMLElement($attributes);
        $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.=$this->data.'</h1>';
        return $this->output;
    }
}
// define concrete class ‘Paragraph’ – extends ‘HTMLElement’
class Paragraph extends HTMLElement{
    var $output='<p ‘;
    var $data;
    function Paragraph($attributes=array(),$data){
        parent::HTMLElement($attributes);
        $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.=$this->data.'</p>';
        return $this->output;
    }
}
// define concrete class ‘UnorderedList’ – extends ‘HTMLElement’
class UnorderedList extends HTMLElement{
    var $output='<ul ‘;
    var $items=array();
    function __construct($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.='<li>’.$item.'</li>';
        }
        $this->output.='</ul>';
        return $this->output;
    }
}

Right, that’s it. As you can see, I’ve first defined a generic, base ‘HTMLElement’ class, and then derived some specific (X)HTML widgets, such as <h1>, <div>, <p> and <ul> elements. Notice how each of these elements provides a concrete implementation for the “getHTML()” method, which was originally defined as abstract in the pertinent base class. So, at this stage I created a well-structured hierarchy of (X)HTML classes, where their objects can be passed to a web page generator class, in order to construct programmatically web documents. Want to learn how this will be done? Fine, move on to the next section and keep on reading.

{mospagebreak title=Building an object-base web page: unexpected results due to the lack of object type checking}

Having written a few (X)HTML widget classes, building a page generator class is a no-brainer process. I just have to define some basic methods and make the class take the widget objects as incoming parameters, in order to generate the web page. So, that’s my theory. Now, take a look at how the page generator class is defined for creating web documents:

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>';
    }
    // the type of input objects is not checked
    function addHTMLElement($htmlElement){
        $this->output.=$htmlElement->getHTML();
    }
    function doFooter(){
        $this->output.='</body></html>';
    }
    function fetchHTML(){
        return $this->output;
    }
}

As you’ll surely agree, the above class is quite primitive, but extremely useful for demonstrating my theory. Notice the signature for the “addHTMLElement()” method, which is definitely the one that does the hardest work of all. As you can see, this method takes an object of type ‘HTMLElement”, then calls its “getHTML()” method, and finally appends the returned code to the class’ general output.

Of course, the big issue worth noting here is that this method isn’t checking the type of object passed as an rgument, which can lead to undesirable results if objects of the wrong type (or even another data structure) are passed as a parameter. Now, are you seeing what I’m pointing out when object type checking is simply skipped?

Now, I’ll translate the above theory into concrete code, in order to clarify what I explained before. Please study the following PHP snippet:

// spawn some HTML elements

$h1=&new Header1(array
(‘name’=>’header1′,’class’=>’headerclass’),’Content for H1
element goes here’);
$div=&new Div(array(‘name’=>’div1′,’class’=>’divclass’),’Content
for Div element goes here’);
$par=&new Paragraph(array
(‘name’=>’par1′,’class’=>’parclass’),’Content for Paragraph
element goes here’);
$ul=&new UnorderedList(array
(‘name’=>’list1′,’class’=>’listclass’),array
(‘item1’=>’value1′,’item2’=>’value2′,’item3’=>’value3′));

// use ‘PageGenerator’ class

$pageGen=&new PageGenerator();
$pageGen->doHeader();
// add ‘HTMLElement’ objects
$pageGen->addHTMLElement($h1);
$pageGen->addHTMLElement($div);
$pageGen->addHTMLElement($par);
$pageGen->addHTMLElement($ul);
$pageGen->doFooter();
// display web page
echo $pageGen->fetchHTML();

As shown above, I’ve spawned some (X)HTML widget objects, which in turn are pushed into the “addHTMLElement()” method of the page generator class, in order to create and display a simple web page. Doing so, I quickly built a web document integrated by an H1 header, then a DIV and a paragraph, and finally an unordered list.

Here, all of the page generation process is performed with no problems, since the objects passed to the page generator class are the correct ones. However, look at the following example, which introduces a minor change to the previous script:

// spawn some HTML elements

$h1=&new Header1(array
(‘name’=>’header1′,’class’=>’headerclass’),’Content for H1
element goes here’);
$div=&new Div(array(‘name’=>’div1′,’class’=>’divclass’),’Content
for Div element goes here’);
$par=&new Paragraph(array
(‘name’=>’par1′,’class’=>’parclass’),’Content for Paragraph
element goes here’);
// create a simple string and pass it to the class
$ul=’This is not a HTML element object!';

// use ‘PageGenerator’ class

$pageGen=&new PageGenerator();
$pageGen->doHeader();
// add ‘HTMLElement’ objects
$pageGen->addHTMLElement($h1);
$pageGen->addHTMLElement($div);
$pageGen->addHTMLElement($par);
$pageGen->addHTMLElement($ul);
$pageGen->doFooter();
// display web page
echo $pageGen->fetchHTML();

When I run the above snippet, this is the output I get on my browser:

Fatal error: Call to a member function on a non-object in
path/to/file/

As you can see, in this case the PHP interpreter complains loudly because I’ve passed to the “addHTMLElement()” method a simple string with the value “This is not a HTML element object!”, which triggers a fatal error when trying to call the corresponding “getHTML()” method of “HTMLElement” objects.

Here, I’ve deliberately contaminated the input of the page generator class with wrong data, but actually this situation could happen under real conditions, with the same (or even worse) results that you just saw. So, what’s the simplest solution for this problem? In short, the class should first check the type of object passed in, before performing its tasks. This operation is known as “object type enforcement,” and certainly is quite easy to implement within a given class.

In order to fix object type issues, I’ll refactor the core “addHTMLElement()”method, so its class can verify whether the type of object being passed on is correct or not. This will prevent eventual problems related to code contamination.

{mospagebreak title=Preventing code contamination: enforcing object types inside of classes}

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!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan