PHP
  Home arrow PHP arrow Page 3 - User-defined Interfaces in PHP 5: Building a Page Generator
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: Building a Page Generator
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2006-01-09


    Table of Contents:
  • User-defined Interfaces in PHP 5: Building a Page Generator
  • Working with multiple interface implementers: defining a page generator class
  • Building object-based web pages: implementing the “PageGenerator” class
  • Full source code: listing the complete 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: Building a Page Generator - Building object-based web pages: implementing the “PageGenerator” class
    ( Page 3 of 4 )

    Considering the (X)HTML widget classes previously defined, as well as the couple of MySQL classes written in the previous article, I’ll build up a sample web page that will include some basic HTML elements, together with a formatted result set obtained from a MySQL query resource. Also, since instantiating (X)HTML objects should be decoupled from the rest of the client code, I’ll define a simple factory class declared abstract, for creating objects. In this way, you’ll see how different objects are used to build a basic web document by utilizing only two classes: the factory class for returning (X)HTML widget objects and the page generator class for displaying the web page.

    Before I code the example, a brief note: if you’re not familiar with the classes developed in previous articles of this series, that shouldn’t be a problem. At the end of this article I’ll provide you with the full list of the source code written during the series, so you’re able to study it.

    Having said that, here is the definition for the factory class, as well the sample code for creating a web page, assuming that the corresponding (X)HTML widget classes have been previously included:

    // class ObjectFactory - returns HTML widget objects
    abstract class ObjectFactory{
        private function __construct(){}
        public function createObject($type,$attributes=array()){
            if(!class_exists($type)||!is_array($attributes)){
                throw new Exception('Invalid object parameters');
            }
            return new $type($attributes);
        }
    }

    // connect to MySQL
    $db=new MySQL(array('host'=>'host','user'=>'user','password'=>'password',
    'database'=>'databasename'));
    // obtain a MySQL result set
    $result=$db->query('SELECT * FROM users');
    // instantiate some (X)HTML widget objects
    $h1=ObjectFactory::createObject('Header1',array('class'=>'header1'));
    $h1->setData('This is a H1 header');
    $h2=ObjectFactory::createObject('Header2',array('class'=>'header2'));
    $h2->setData('This is a H2 header');
    $h3=ObjectFactory::createObject('Header3',array('class'=>'header3'));
    $h3->setData('This is a H3 header');
    $h4=ObjectFactory::createObject('Header4',array('class'=>'header4'));
    $h4->setData('This is a H4 header');
    $h5=ObjectFactory::createObject('Header5',array
    ('class'=>'header5'));
    $h5->setData('This is a H5 header');
    $table=ObjectFactory::createObject('Table',array
    ('width'=>'500','class'=>'datatable'));
    $table->setData(array('FirstName'=>'John','LastName'=>'Doe'));
    $form=ObjectFactory::createObject('Form',array
    ('action'=>'formprocessor.php','method'=>'post'));
    $form->setData('Please enter your data below');
    // add form fields
    $form->addInputField(array
    ('type'=>'text','name'=>'fname','size'=>'30'),'First Name');
    $form->addInputField(array
    ('type'=>'text','name'=>'lname','size'=>'30'),'Last Name');
    $form->addInputField(array
    ('type'=>'text','name'=>'email','size'=>'30'),'Email');
    $form->addTextArea(array
    ('name'=>'comments','rows'=>'20','cols'=>'30'));
    $form->addInputField(array
    ('type'=>'submit','name'=>'send','value'=>'Send Data'));
    $form->addSelectField(array('name'=>'options'),array
    ('value1'=>'1','value2'=>'2','value3'=>'3'));
    $div=ObjectFactory::createObject('Div',array
    ('id'=>'content','class'=>'divs'));
    // set div data
    $div->setData('Div content');
    $firstPar=ObjectFactory::createObject('Paragraph',array
    ('class'=>'paragraph'));
    // set paragraph data
    $secondPar=ObjectFactory::createObject('Paragraph',array
    ('class'=>'paragraph'));
    $secondPar->setData('Paragraph data');
    // set paragraph data
    $firstPar->setData($secondPar);
    // instantiate a new PageGenerator object
    $pageGen=new PageGenerator();
    // build page header
    $pageGen->makeHeader();
    // add HTML renderable objects
    $pageGen->addHTMLRenderableObject($h1);
    $pageGen->addHTMLRenderableObject($h2);
    $pageGen->addHTMLRenderableObject($h3);
    $pageGen->addHTMLRenderableObject($h4);
    $pageGen->addHTMLRenderableObject($h5);
    $pageGen->addHTMLRenderableObject($firstPar);
    $pageGen->addHTMLRenderableObject($table);
    $pageGen->addHTMLRenderableObject($div);
    $pageGen->addHTMLRenderableObject($form);
    $pageGen->addHTMLRenderableObject($result);
    // build page footer
    $pageGen->makeFooter();
    // generate web page
    echo $pageGen->getHTML();

    As you can see in the above example, I’ve connected to MySQL, then run a SELECT statement and returned a formatted result set containing data from a “users” table. Next, a few (X)HTML widget objects have been instantiated through the factory class, including some headers, a table, a div element, two paragraphs and finally a regular form.

    Finally, the web page was created by following three logical steps: first the header was generated, next the body section was assembled by using the objects implementers of the “HTMLRenderer” interface, and finally the footer was appended to the page’s output.

    Of course, the most relevant aspect within the page generation process is how the body section is constructed. Notice that each “renderable” object is appended to the page using the “addHTMLRenderableObject()” method, which was fully explained before. As I said previously, the direct advantage of this method resides in its flexibility for accepting “HTMLRenderer” interface implementers, whether or not the objects are of the same type. Because of this capability, it’s possible to include within the same page whether (X)HTML widgets or formatted result-type objects. The following two lines of code take up this idea:

    $pageGen->addHTMLRenderableObject($form);
    $pageGen->addHTMLRenderableObject($result);

    As you can appreciate, the same method is used to include different types of objects in the construction of the web page, as long as the objects implement the same interface. This single concept should get you started with your own ideas about how to take advantage of interfaces in your PHP programs.

    Besides showing interface capabilities, the example demonstrates yet another powerful technique. Due to the fact that (X)HTML widgets were defined to support a recursive implementation, it’s possible to build nested structures by only passing one object as an argument of another through its “setData()” method. How is it done? To clarify this idea, take a look at the example below, where the formatted result set is wrapped into a <div> container:

    // connect to MySQL
    $db=new MySQL(array('host'=>'host','user'=>'user','password'=>'password',
    'database'=>'databasename'));
    // obtain a MySQL result set
    $result=$db->query('SELECT * FROM users');
    // instantiate some (X)HTML widget objects
    $h1=ObjectFactory::createObject('Header1',array('class'=>'headers'));
    $h1->setData('This is the header of the page);
    $div=ObjectFactory::createObject('Div',array
    ('id'=>'content','class'=>'divs'));
    // set a $result object as div argument
    $div->setData($result);
    // instantiate a new PageGenerator object
    $pageGen=new PageGenerator();
    // build page header
    $pageGen->makeHeader();
    // add HTML renderable objects
    $pageGen->addHTMLRenderableObject($h1);
    $pageGen->addHTMLRenderableObject($div);
    // build page footer
    $pageGen->makeFooter();
    // generate web page
    echo $pageGen->getHTML();

    What I’ve done here is obtain a MySQL result set and pass it directly to a “Div” widget as its argument, instead of using a regular string. The result of the above snippet is a web page comprised of a <h1> header, as well as the formatted query resource wrapped into a <div> containing element. Because of the flexibility of this technique, nesting multiple objects is supported, thus more complex page layouts are easily achieved. It’s just a matter of playing around with objects.

    By this point, hopefully you’ve understood that the benefits of applying interfaces in PHP programs are certainly numerous. Most of these advantages are more evident when an application requires working with objects of different types that share a common set (or multiple sets) of abstract methods, which are concretely implemented by each referenced object within its class definition.

    Now that you’ve learned about the basics of user-defined interfaces, as well as their implementation in PHP programs, you can go further and start using them in your own web applications.



     
     
    >>> 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