Home arrow PHP arrow Page 3 - User-defined Interfaces in PHP 5: Building a Page Generator

Building object-based web pages: implementing the “PageGenerator” class - PHP

In this final part of the series on user-defined interfaces in PHP 5, Alejandro puts all of the classes created in the previous articles together to work as a page generator. This allows complex page generation to be translated into a more flexible process through an object-based solution.

TABLE OF CONTENTS:
  1. User-defined Interfaces in PHP 5: Building a Page Generator
  2. Working with multiple interface implementers: defining a page generator class
  3. Building object-based web pages: implementing the “PageGenerator” class
  4. Full source code: listing the complete classes
By: Alejandro Gervasio
Rating: starstarstarstarstar / 12
January 09, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: