In its most common configuration, PHP relies on the web server to do the routing. This is done by mapping the request path to a file: If you request www.example.org/test.php, the web server will actually look for a file named test.php in a pre-defined directory.
There is a feature that comes in handy for our purpose: Many web servers also allow you to call www.example.org/test.php/hello and it will still execute test.php. PHP makes the additional stuff in the requested path accessible via the $_SERVER['PATH_INFO']
variable. In this case it would contain "/hello".
Using this, we can build a very simple router like this:
<?php
// First, let's define our list of routes.
// We could put this in a different file and include it in order to separate
// logic and configuration.
$routes = array(
'/' => 'Welcome! This is the main page.',
'/hello' => 'Hello, World!',
'/users' => 'Users!'
);
// This is our router.
function router($routes)
{
// Iterate through a given list of routes.
foreach ($routes as $path => $content) {
if ($path == $_SERVER['PATH_INFO']) {
// If the path matches, display its contents and stop the router.
echo $content;
return;
}
}
// This can only be reached if none of the routes matched the path.
echo 'Sorry! Page not found';
}
// Execute the router with our list of routes.
router($routes);
?>
For the sake of simplicity, I did not make the router a class. But from here on, that shouldn't be a problem either.
Let's assume we named this file index.php. We can now call www.example.org/index.php/hello to get a nice "Hello, World!" message. Or www.example.org/index.php/ to get the main page.
The "index.php" in that URL is still ugly, but we can fix this by using URL rewriting. In Apache HTTPD you would put a .htaccess
file in the same directory with the following content:
RewriteEngine on
RewriteRule ^(.*)$ index.php/$1
And there you are! Your very own router with under 10 lines of logic code (not counting comments and the routes list).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…