Click here to Skip to main content
Full site     10M members (36.2K online)    

Write a router for PHP MVC Applications

Introduction 

PHP MVC pattern has a router for giving data to the controller and to process it. The router has an action and a parameter, like this:

http://example.com/post/3

In this tip, we want to create a router like this:

http://example.com/index.php/post/hello-world 

We should use $_SERVER['PHP_SELF'] to create this.

Using the Code 

Now, we explode $_SERVER['PHP_SELF'] for detecting action and parameters, so input this code in your controller and include it in index.php:

public function router() {
    $rt = $_SERVER['PHP_SELF'];
    $rt = explode('/',$rt);

    $this -> action    = $rt[2];
    $this -> parameter = $rt[3];
}

public function isValidRt() {
    error_reporting(E_ALL ^ E_NOTICE);
    $rt = self::router();
    if(!is_numeric($this -> action && $this -> parameter)) {
        die(include('404.php'));
    }
    else {
        return $rt;
    }
}  

posts is action and parameter is hello-world.

you can use isValidRt() to use router.

You have these two variables! You can use them. Wink | ;)

 

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search 
Per page   
-- There are no messages in this forum --

Last Updated 13 May 2013 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2013