Hudzilla.org - the homepage of Paul Hudson
Contents > Objects > The Object-Oriented Website Wish List | Report Bug | About Me ]

6.19.1     A basic OOP site

This is NOT the latest copy of this book; click here for the latest version.

The first thing we're going to produce will be a very simple OOP site that has a site class, csite, and a page class, cpage. These two classes will be kept "clean" in that they won't have any idea of the design of the site around them or their content - they'll just render themselves. This means we'll need several site-specific files as well.

First, let's look at the contents of an example file in our site, index.php:

<?php
    
include 'stdlib.php';

    
$site = new csite();

    
// this is a function specific to this site!
    
initialise_site($site);

    
$page = new cpage("Welcome to my site!");
    
$site->setPage($page);

    
$content = <<<EOT
Welcome to my personal web site!
EOT;
    
$page->setContent($content);

    
$site->render();
?>

The stdlib.php file will contain the site-specific information - all the information that shouldn't be inside our classes and shouldn't be repeated in every page. We set $site to be an instance of our site, and then call a function called initialise_site() to set it up with our basic, site-specific settings - that function will be in stdlib.php.

Next we create a cpage object, passing into the constructor the title of the page, then use the setPage() function of our csite class to add the page to our site for rendering.

The next few lines set up the page-specific content for our cpage, and then calls the setContent() function of the object to add the text to the page. Finally, we call the render() function of our csite object to output the HTML.

Don't worry if that's all as clear as mud right now - we've yet to look at the other files involved. Here's stdlib.php:

<?php
    
function __autoload($class) {
        include
"$class.php";
    }

    function
initialise_site(csite $site) {
        
$site->addHeader("header.php");
        
$site->addFooter("footer.php");
    }
?>

The first part is the magic __autoload() function. Note how in index.php we don't specify either csite or cpage - we just presume they exist. This is accomplished through the magic __autoload() function, but, when you think about it, that function couldn't go inside one of the classes (there's a recursive bit of logic there!), and neither should it be replicated inside each of the page-specific scripts, as that would be a nightmare to maintain. So, it's in stdlib.php.

The second part is the initialise_site() function, where we add site-specific header and footer files for this site. The addHeader() and addFooter() functions are both part of the csite class, which we'll look at in a moment. Note that the __autoload() function will look for csite.php and cpage.php, so we need to supply those two. Here's csite.php:

<?php
    
class csite {
        private
$headers;
        private
$footers;
        private
$page;

        public function
__construct() {
            
$this->headers = array();
            
$this->footers = array();
        }

        public function
__destruct() {
            
// clean up here
        
}

        public function
render() {
            foreach(
$this->headers as $header) {
                include
$header;
            }

            
$this->page->render();

            foreach(
$this->footers as $footer) {
                include
$footer;
            }
        }

        public function
addHeader($file) {
            
$this->headers[] = $file;
        }

        public function
addFooter($file) {
            
$this->footers[] = $file;
        }

        public function
setPage(cpage $page) {
            
$this->page = $page;
        }
    }
?>

The $headers and $footers variables are both arrays that will store file names of scripts to include at render-time - they are both initialised to be empty arrays when the site is created. The setPage() function takes a cpage object (note the type hint!), and stores it away for rendering.

The main function here is clearly render(), which is what the converts the various disparate parts into a working HTML file. It does that by first including each of the scripts stored in $headers, then calling the render() function of the cpage object, then including all the footer files. In reality it's not likely a site will have more than one header and footer file, but there's no harm being flexible!

Next up, the cpage.php file - here it is:

<?php
    
class cpage {
        private
$title;
        private
$content;

        public function
__construct($title) {
            
$this->title = $title;
        }

        public function
__destruct() {
            
// clean up here
        
}

        public function
render() {
            echo
"<H1>{$this->title}</H1>";
            echo
$this->content;
        }

        public function
setContent($content) {
            
$this->content = $content;
        }
    }
?>

So we've got $title and $content variables there, which is predictable enough. Note how the constructor takes the page title as its only parameter - if you look back to index.php you'll see that being used. The setContent() function is pretty predictable, as is the main render() function itself - it's all very basic right now.

The header.php file is site-specific, and so could be anything you want. Here's an example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>My Website</TITLE>
</HEAD>

<BODY>

Here's a footer.php example also:

</BODY>
</HTML>

That finishes up the code example - go ahead and run it, and you should see a very simple site being outputted. This is one of the big downsides to using OOP for your site: it takes an awful lot of work to get very little. Of course, once you've done that work, the rest of the site is quite easy!





<< 6.19 The Object-Oriented Website   6.19.2 A more complex OOP website >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
doc776 - 07 Sep 2008

awesome tutorial, i spent like 4 hours messing around to create my own oop site, and this tutorial did the basics.

tip: at the end write some interesting things that could be added in different places of the script.

ptrpan - 07 Sep 2008

could it be version incompatability?

ptrpan - 07 Sep 2008

i get this error when i try to load the page

Parse error: parse error, expecting `')'' in C:\Xitami\webpages\testsite\stdlib.php on line 6

PHP version is 4.3.11

A PHP User - 07 Sep 2008

$this->page->render() will run the render function of the cpage object. in other words:

it will wrap the contens of the page into the header(s) and the footer(s)

site
---header(s)
---header(s)
---content_of_the_PAGE
---footer(s)
---footer(s)

PHP n00b - 07 Sep 2008

This didnt work for me. I copied all the code into all the files. Then, when I loaded Index.php, i got two errors:

Parse error: parse error, unexpected T_STRING, expecting ')' in \\192.168.1.16\webfiles\files\2006-3\695610\stdlib.php on line 6

Fatal error: Cannot instantiate non-existent class: csite in \\192.168.1.16\webfiles\files\2006-3\695610\index.php on line 4

Silviu - 07 Sep 2008

Now I know why when I have tried the example in php 5.0.3 doesn't work.
It was because I have
zend.ze1_compatibility_mode = On
If I will turn to Off then the example will work.

Silviu - 07 Sep 2008

I know now what was the problem.
With zend.ze1_compatibility_mode = Off it works but having
zend.ze1_compatibility_mode = On it does't work as expected.

Silviu - 07 Sep 2008

In php 5.0.3 doesn't work as expected,the output is only this:
"<H1>Welcome to my site!</H1>".
I have also try this example with php 5.0.4 on another computer and there it works just fine.
What could be the problem? I think I will upgrade very soon.

.Gx. - 07 Sep 2008

@keithcelt -a-t- yahoo.com,

It displays the page's title and content.
Not a bad tutorial but the structure aint right to me (maybe im wrong).

/***/
foreach($this->headers as $header)
{
include $header;
}
/***/

why would a page have multiple headers? same goes for footer.

I am also building a site using OOP but my approach is totally different.

i have a page class wich loads all my modules(wich give the page who created them, the values they fetched in an array that is merged with the other variables)

from there i load a template again telling it wich page is loading if.

for example

public funcion loadTemplate($template, $page)
{
require_once($template);
}


and in the template i would have for example:
<H1>{<?=$page->GetValue("title");?>}</H1>
wich would echo the index title out of the variables array if exist.


an other way could be:

public funcion loadTemplate($template, $page)
{
extract ( $page->GetValues() ) //check php API for extract
require_once($template);
}

extract will convert each array index into variables.
in this case in the template i would have for example:
<H1>{<?=$title;?>}</H1>
wich would echo the index title out of the variables array if exist.

hmmz gotta continue working now or i would write a bit more.

i am wanting to help anyone if needed(We both can learn fro m it) as long as i dont get spammed badle >_>

my email is gee_x37@hotmail.com

hendrik - 07 Sep 2008

it dereferences the page object stored as a member variable of the csite-class and propagates the call to the render-method of the page object, i.e. calling site->render will call page->render.

keithcelt -a-t- yahoo.com - 07 Sep 2008

What is this line for?


$this->page->render();

From what I read it makes no sense. Isnt it a recursive call to render() since it is inside render when this line is read/written? I hope thad made sense :)

Thanks,

Keith



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is nine plus four?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow