Examples

The coming examples assume/need the following setup:

.htaccess


DirectoryIndex router.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !\.(js|ico|gif|jpg|png|css)$ /router.php

init.php

<?php
require_once 'Net/URL/Mapper.php';
$m Net_URL_Mapper::getInstance();
?>

Blog routing

The following snippets maps a couple blog URLs.

blog-router.php

<?php
require 'init.php';

$m->connect('blog', array('page' => 'frontpage.php'));
$m->connect(
    
'blog/feed/:type',
    array(
'page' => 'feed.php''type' => 'rss')
);
$m->connect(
    
'blog/archives/:year/:month',
    array(
        
'page' => 'archive.php',
        
'year' => date('Y'),
        
'month' => date('m')
    )
);

$route $m->match($_SERVER['REQUEST_URI']);
if (
$route === null) {
    
// no match
    
$route = array(
        
'page' => 'frontpage.php',
    );
}
include 
dirname(__FILE__) . '/inc/' $route['page'];
?>

Zend Framework routing

A really simple example for Zend Framework-style URL routing. ;-) This is not meant to work in production, it's not necessarily secure and serves as a proof of concept or base for a real implementation.

zf-router.php

<?php
require 'init.php';

$path     '/:module/:controller/:action';
$defaults = array(
    
'module'     => 'default',
    
'controller' => 'index',
    
'action'     => 'index',
);

$m->connect($path$defaults);

$route $m->match($_SERVER['REQUEST_URI']);

// Fix the controller's name to adhere to ZF's standard, FooController
$controllerClass  ucfirst(strtolower($route['controller'])) . 'Controller';

// Fix the action's name to adhere to ZF's standard, barAction()
$controllerAction strtolower($route['action']) . 'Action';

// load the controller class
require 'app/modules/' $route['module'] . '/' $class '.php';

$controllerObj = new $controllerClass;
call_user_func(array($controllerObj$controllerAction)); // pseudo dispatcher
?>

Generate a URL

The following snippet explains how to generate a fancy URL automatically from the defined routes.

generate-url.php

<?php
require 'init.php';

$m->connect('blog', array('page' => 'frontpage.php'));
$m->connect(
    
'blog/feed/:type',
    array(
'page' => 'feed.php''type' => 'rss')
);
$m->connect(
    
'blog/archives/:year/:month',
    array(
        
'page' => 'archive.php',
        
'year' => date('Y'),
        
'month' => date('m')
    )
);

$url1 $m->generate(array(
    
'page' => 'feed.php',
    
'type' => 'atom',
)); 
// blog/feed/atom

$url2 $m->generate(array(
    
'page'  => 'archive.php',
    
'year'  => '2008',
    
'month' => '06',
)); 
// blog/archives/2008/06

?>