The coming examples assume/need the following setup:
.htaccess
init.php
<?php
require_once 'Net/URL/Mapper.php';
$m = Net_URL_Mapper::getInstance();
?>
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'];
?>
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
?>
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
?>