Completing an Extensible Website Engine with PHP 5

Are you one of those web developers searching for a comprehensive approach to constructing an expandable website engine with PHP 5? If your answer is a resounding yes, then this series might appeal to you. Welcome to the final part of the series “Building an extensible website engine with PHP 5.” In two tutorials, this series teaches you how to build a versatile website system which allows you to generate dynamic web documents by using a few simple PHP classes.

If you just read the above introduction, then you know that this series contains a preceding article. In that article, I introduced the basics of how to build a simple (but highly extensible) mechanism for creating dynamic web pages, based on a pre-established database schema as well as on a single template file.

Of course, since the structure of this system is extremely flexible, you can expand it as far as you want to build more complex websites and satisfy more demanding requirements. True to from, from the beginning, this series has been conceived only as an introduction for those web developers that want to dig deeper into the terrain of database-driven websites.

Having clarified some points regarding the topics covered in the first tutorial, along with the general goals of the series, it’s time to move on and take the next step toward the development of the PHP 5-based website engine. Therefore, over the course of this final article, you’ll learn how to build a “pluggable” web page generation system, which can be easily extended to be used in conjunction with any conventional Content Management System.

With the preliminaries out of our way, let’s find out together how this website engine will be progressively developed. Let’s go!

{mospagebreak title=Pulling web page contents from a database table}

Due to the fact that the whole website engine will be fetching web page contents straight from the “pages” database table that was originally defined in the first article, the initial step involved in this project consists of creating a simple mechanism that allows for interaction with MySQL.

In response to the requirements mentioned above, I’ll define a couple of PHP classes tasked with handling all the processes related to connecting to MySQL and selecting databases, as well as executing SQL queries.

The respective signatures of these two MySQL processing classes are listed below:

// define ‘MySQL’ class
class MySQL{
    private $conId;
    private $host;
    private $user;
    private $password;
    private $database;
    private $result;
    public function __construct($options=array()){
            throw new Exception(‘Invalid number of connection
        foreach($options as $parameter=>$value){
                throw new Exception(‘Invalid parameter
    private function connectDB(){
            throw new Exception(‘Error connecting to the
            throw new Exception(‘Error selecting database’);
    public function query($query){
            throw new Exception(‘Error performing query
        return new Result($this,$this->result);
// define ‘Result’ class
class Result {
    private $mysql;
    private $result;
    public function __construct(&$mysql,$result){
    public function fetchRow(){
        return mysql_fetch_assoc($this->result);
    public function countRows(){
            throw new Exception(‘Error counting rows’);
        return $rows;
    public function countAffectedRows(){
            throw new Exception(‘Error counting affected rows’);
        return $rows;
    public function getInsertID(){
            throw new Exception(‘Error getting ID’);
        return $id;
    public function seekRow($row=0){
            throw new Exception(‘Invalid result set offset’);
            throw new Exception(‘Error seeking data’);
    public function fetchFormattedResult($query,$closeTag='</p>’){
            throw new Exception(‘Query must begin with SELECT’);
        return $output;

If you take some time and examine the source code of the above two classes, then you’ll possibly find them familiar, since I’ve been using them in some of my previous PHP articles.

On the other hand, if this doesn’t ring any bells to you, let me tell you that the first “MySQL” class is a simple wrapper. It’s handy for connecting to the server, selecting a particular database, and running queries. The second one is responsible for performing a few useful tasks regarding the manipulation of result sets, like fetching and counting returned rows, and others.

At this point, I can say that the pair of MySQL processing classes that you saw previously are the first building blocks of the website engine that I’m currently building. They will handle all the processes required for fetching web page contents from the “pages” database table. Sounds logical, right?

Now, as you’ll probably recall, the entire presentation layer that corresponds to this website engine was completely handled by a single template file called “default_template.htm,” which also was created over the course of the first tutorial of the series. Keeping in mind this condition, it’s obvious that some kind of mechanism for processing that template is required here.

In order to tackle all the tasks for parsing the mentioned template file, in the following section I’ll be defining a useful template processing class with PHP 5. It will be charged first with taking up all the web page data pulled from the corresponding database table, and second with injecting this data straight into the respective template file.

After defining this template processing class, the PHP 5-based website engine that I originally planned to create will be near to completion, so hurry up and read the following section!

{mospagebreak title=Injecting web page contents into the template file}

As I said in the previous section, to complete the pertinent website engine, it’s necessary to add an additional component to it, which will be responsible for parsing the respective template file. In this way, both the data and presentation layers will be interconnected to each other by the couple of MySQL processing classes shown previously, as well as by the template processor that I’m just about to create.

With reference to the template processor class, please take a look at its source code, which is listed below:

class TemplateProcessor {
    private $output=”;// set default value for overall class
    private $rowTag=’p’;// set default value for database row tag
    private $tags=array();// set default value for tags
    private $templateFile=’templates/default_template.htm’;// set
default value for template file
    private $cacheFile=’cache/default_cache.cache’;// set default
value for cache file
    private $expiry=1;// set default value for cache expiration
    public function __construct($tags=array()){
            throw new Exception(‘Invalid number of tags’);
            // read data from cache file
            // read template file
            // process template file
            // clean up empty tags
            // write compressed data to cache file
        // send gzip encoding http header
    // check cache validity
    private function isCacheValid(){
        // determine if cache file is valid or not
            return true;
        return false;
    // process template file
    private function processTemplate($tags){
        foreach($tags as $tag=>$data){
            // if data is array, traverse recursive array of tags
            // if data is a file, fetch processed file
            // if data is a MySQL result set, obtain a formatted
list of database rows
            elseif(@get_resource_type($data)==’mysql result’){
                    foreach($row as $col){
            // if data contains the ‘[code]’ elimiter, parse data
as PHP code
        // clean up empty tags
    // process input file
    private function processFile($file){
          return $contents;
    // write compressed data to cache file
    private function writeCache(){
            throw new Exception(‘Error writing data to cache
    // read compressed data from cache file
    private function readCache(){
            throw new Exception(‘Error reading data from cache
        return $cacheContents;
    // return overall output
    public function getHTML(){
          return $this->output;
    // return compressed output
    private function getCompressedHTML(){
        // check if browser supports gzip encoding
            // start output buffer
            // echo page contents to output buffer
            echo $this->output;
            // compress (X)HTML output with gzip
            // clean up output buffer
            // return compressed (X)HTML content
            return $this->output;
        return false;
    // send gzip encoding http header
    private function sendEncodingHeader(){
        header(‘Content-Encoding: gzip’);

As shown above, the “TemplateProcessor” class has some handy methods for replacing all the placeholders contained inside the “default_template.thm” file with actual web page data. Aside from the functionality that I just mentioned, this class is also capable of caching the parsed template during a given period of time, as well as sending parsed contents as compressed data via the “Gzip” compression algorithm.

However, it’s important to notice here that the “TemplateProcessor” class is itself the other critical part of the website engine. When used in conjunction with the previous MySQL processing classes, it is capable of generating true dynamic web pages even when the website’s whole structure is static (remember that each web document is created basically from the same “default_template.htm” file).

All right, now you’ve seen separately how each part of the website engine does its thing. On one hand you learned how to fetch the contents of each web page, while on the other hand you saw how these contents are injected straight into the previously defined template file. But how can these parts work together to implement a fully-functional website engine?

Well, in the next section, I’ll use all the classes that I defined before so you can see how this PHP 5-based website engine can generate web pages on the fly.

To learn how this will be achieved, all you have to do is click on the link shown below and keep reading. We’re almost finished!

{mospagebreak title=The website engine in action}

Although I showed you in separate pieces how the contents of the respective “page” database table can be used for creating dynamic web pages, the real power of the website engine developed here is revealed when all the previous classes are put to work on the same PHP file.

To illustrate more clearly the entire process for generating the different web pages that I showed you in the first article, say you want to implement the website engine on just one file, called “index.php.” Based on this premise, this file would look as follows:

    // include class files
    require_once ‘classes/template_processor_class.php’;
    require_once ‘classes/mysql_class.php’;
    // connect to MySQL
    $db=new MySQL(array(‘host’=>’host’,’user’=>’user’,’password’=>’password’,
    // fetch page contents from database
    $result=$db->query(“SELECT * FROM pages WHERE id=$pageid”);
        throw new Exception(‘Error fetching page contents’);
    // build array of tags
    //instantiate template processor object
    $tpl=new TemplateProcessor($tags);
    // display compressed page
    echo $tpl->getHTML();
catch(Exception $e){
    echo $e->getMessage();

Believe or not, this is all the PHP code that you need to create the different web pages that compose the whole website. If you dissect the above script into pieces, you’ll see it first includes all the classes that were created previously, then connects to MySQL and finally fetches from the “pages” database table all the web document contents that correspond to a specific value of the “$pageid” GET variable. Wasn’t that easy?

Of course, once page data has been properly returned to the script, each section of the web document (that is the header, the left, right and center columns, and the footer respectively) is dynamically generated by using the template processor class. With reference to this process in particular, the following line:


demonstrates in a clear fashion how each web page section is created on the fly with contents pulled from the “pages” database table. Now, do you see how the website engine works with only one “$pageid” parameter?

Just think about working with more tables, which can be filled via your favorite CMS. Certainly, possibilities are numerous!

Final thoughts

In this two-part series, I gave you some useful pointers on how to build an expandable website engine that uses PHP 5 as the primary scripting language for generating web pages on the fly. Even when the system may not fit all your needs, I think it can be considered a good option, particularly when you want to create a database-driven website without having to work with multiple databases.

As usual, see you in the next PHP tutorial!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye