[Solved] How to create php class for navigation action


Assume we have the following rewrite rule;

RewriteEngine On
RewriteRule ^([^/]*)$ /index.php?module=$1 [L,QSA] 

This will rewrite a request like; http://example.php/index.php?module=about to http://example.php/about

Now, let’s see how the Router is done;

  • It’s very basic
  • Can be improved a lot
<?php

class Router {
    private $strModule;     //Holds the module to load (the page)

    public function __construct(){}

    public function setModule($strModuleName) {
        $this->strModule = $strModuleName;
    }

    public function loadModule() {
        if( file_exists('modules/'. $this->strModule .'.php') ) {
            include 'modules/'. $this->strModule .'.php';
        } else {
            'modules/404.php';
        }
    }

}

Now, let’s use the router in index.php

$objRouter = new Router();
$objRouter->setModule($_GET['module']);
$objRouter->loadModule();

And our tree will be like;

 - index.php
 - modules/
    - about.php
    - 404.php

Of course, this is just a quick job, and it can be improved a lot.

I hope that helps.

Note:
The pretty urls (.htaccess rewrite rules) are just for eye-candy. You can achieve this by not using rewrite rules, even with the same code supplied above

0

solved How to create php class for navigation action