Most PHP frameworks use some variation of the front controller pattern to centralize common code and logic. There are advantages and disadvantages to this. I am going to ignore those for now. In fact the first part of this series will explore a simple procedural URL routing method that contains many of the disadvantages. In later articles we will build upon this basis and address the disadvantages.
Requirements
- PHP
- Apache with mod_rewrite enabled.
Redirecting with mod_rewrite
This article doesn’t discuss mod_rewrite and the .htaccess in detail, the following .htaccess file is sufficient for the needs of our simple front controller. The .htaccess file should be placed in the same directory as the front controller script. All requests will be sent to index.php while requests for a file or directory that does exist will bypass the mod_rewrite rules and be served directly by the web server.
file: .htaccess
-
Options +FollowSymLinks
-
IndexIgnore */*
-
# Turn on the RewriteEngine
-
RewriteEngine On
-
# Rules
-
RewriteCond %{REQUEST_FILENAME} !-f
-
RewriteCond %{REQUEST_FILENAME} !-d
-
RewriteRule . index.php
The Entry Point
I chose a simple format for the incoming URL, a command followed by its parameters separated by forward slashes “/”.
For example:
www.example.com/command/parameter1/parameter2/
in this example $requestURI would contain.
This works fine except in the case where the front controller is not in the root directory.
For example:
www.example.com/myapps/app1/command/parameter1/parameter2/
in this case $requestURI would contain.
-
Array ( [0] => [1] => myapps [2] => app1 [3] => command [4] => parameter1 [5] => parameter2 [6] => )
To filter out the path to the front controller we will need to use the $_SERVER['SCRIPT_NAME'] variable.
In the above example $scriptName would contain.
Array ( [0] => [1] => myapps[2] => app1 [3] => index.php )
Which can be used to remove the path and script name from the URI.
Note: As you can see the explode method leaves an empty array member at the first position. This will be fixed by the following code.
-
-
{
-
if ($requestURI[$i] == $scriptName[$i])
-
{
-
}
-
}
-
After the code above $command would contain.
Array ( [0] => command [1] => parameter1 [2] => parameter2 [3] => )
Dispatching the command
Now that we have a command with its parameters stored in an array it is trivial to handle them via a switch statement. The following is a short example.
-
switch($command[0])
-
{
-
-
case ‘commandOne’ :
-
break;
-
-
case ‘commandTwo’ :
-
break;
-
-
default:
-
echo ‘That command does not exist.’;
-
break;
-
}
Try it out
You can visit examples.phpaddiction.com/urlrouter/part_1/ to see it in action and download the sample code.
Next up
The next part in the series will focus on moving the URL router into a class and out of the global namespace.
Update I’ve updated the .htaccess per the comment made by DrBacchus.
MAR

About the Author