Home arrow PHP arrow Page 4 - Developing the Router/Dispatcher Class for a Simple MVC-based Framework in PHP 5

Listing the framework’s partial source code - PHP

In this second part of the series, I add another crucial component to this example MVC-driven framework. It's a basic router/dispatcher class. While the incorporation of this brand new module turns the framework into a more functional piece of code, there are other components that still need to be developed.

TABLE OF CONTENTS:
  1. Developing the Router/Dispatcher Class for a Simple MVC-based Framework in PHP 5
  2. Review: start building the MVC-based framework
  3. Building the router/dispatcher class
  4. Listing the framework’s partial source code
By: Alejandro Gervasio
Rating: starstarstarstarstar / 4
June 08, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

As I promised in the segment that you just read, below I included all of the  framework’s source files created so far, so you can see more clearly how they interact with each other.

Having said that, here are the files in question, starting with the definition of the default “.htaccess”: 

(.htaccess file)

# Turn on URL rewriting engine

RewriteEngine On

# Disable rewriting for existing files or directories

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

# redirect all other requests to index.php

RewriteRule ^.*$ index.php [PT,L]

Now, it’s time to look at the framework’s front controller:

(index.php)

<?php

// framework’s front controller

// specify parameters for autoloading classes

spl_autoload_register(NULL, FALSE);

spl_autoload_extensions('.php');

spl_autoload_register(array('Autoloader', 'load'));

// define custom ClassNotFoundException exception class

class ClassNotFoundException extends Exception{}

// define Autoloader class

class Autoloader

{

                // attempt to autoload a specified class

                public static function load($class)

                {

                                if (class_exists($class, FALSE))

                                {

                                                return;

                                }

                                $file = $class . '.php';

                                if (!file_exists($file))

                                {

                                                eval('class ' . $class . '{}');

                                                throw new Exception('File ' . $file . ' not found.');

                                }

                                require_once($file);

                                unset($file);

                                if (!class_exists($class, FALSE))

                                {

                                                eval('class ' . $class . '{}');

                                                throw new ClassNotFoundException('Class ' . $class . ' not found.');

                                }

                }

}

// handle request and dispatch it to the appropriate controller

try{

                Dispatcher::dispatch();

}

catch (ClassNotFoundException $e){

                echo $e->getMessage();

                exit();

}

catch (Exception $e){

                echo $e->getMessage();

                exit();

}// End front controller

And finally, this showcase of files finishes with the inclusion of the router/dispatcher module:

(Dispatcher.php)

<?php

class Dispatcher

{

    // dispatch request to the appropriate controller/method

    public static function dispatch()

    {

                $url = explode('/', trim($_SERVER['REQUEST_URI'], '/'));

                array_shift($url);

        // get controller name

        $controller = !empty($url[0]) ? $url[0] . 'Controller' : 'DefaultController';

        // get method name of controller

        $method = !empty($url[1]) ? $url[1] : 'index';

        // get argument passed in to the method

        $arg = !empty($url[2]) ? $url[2] : NULL;

        // create controller instance and call the specified method

                                 $cont = new $controller;

        $cont->$method($arg);

    }

}// End Dispatcher class

There you have it. At this point you’ll have to agree with me that the structure of this example MVC-based framework looks much better, due to the addition of the router/dispatcher class. However, there’s still a long way ahead of us, since the framework will include some other modules that will be created in forthcoming tutorials of the series.

Meanwhile, feel free to tweak the code of the classes and configuration files shown so far, which hopefully will give you a better grounding in combining the functionality of the MVC design pattern and the object-oriented paradigm in PHP 5.  

Final thoughts

Over this second installment of the series, I added another crucial component to this example MVC-driven framework, which turned out to be a basic router/dispatcher class. Even though the incorporation of this brand new module turns the framework into a more functional piece of code, there are still many other components that need to be developed.

In consonance with this requirement, in the upcoming tutorial I’m going to build another class whose main function will be abstracting accesses to the framework’s underlying storage mechanism, which for this specific project will be a MySQL database.

To learn more on how this MySQL abstraction class will be constructed in some simple steps, don’t miss the next article!



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