HomePHP Page 2 - Building a Simple MVC-based Framework in PHP 5
Routing all HTTP requests to the front controller - PHP
In this first part of a series, I develop the first module of a model-view-controller (MVC) driven framework, which happens to be a front controller. By combining this component and a basic .htaccess file, it’s possible to route all HTTP requests to the (still-undefined) dispatcher class.
As I stated at the beginning, the MVC-based framework that I'm going to build over the course of this series will make use of the front controller pattern to route all of the HTTP requests through a unique file. In accordance with most standard web server configurations, this file will be called “index.php.”
Even though it’s possible to create a PHP script that performs this routing process, the easiest way to achieve this is by means of a simple .htaccess file -- assuming that the framework will run on an Apache server with its mod_rewrite module enabled, which is a pretty common scenario.
Thus, the first thing we must do is create the file, which will look like this:
# Turn on URL rewriting engine
RewriteEngine On
# Disable rewriting for existing files or directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# redirect all other requests to index.php
RewriteRule ^.*$ index.php [PT,L]
If you’ve ever used mod_rewrite under Apache, then the definition of the previous .htaccess file should be very easy to grasp. As you can see, the file first turns on the server’s rewriting engine, and then redirects all of the requests to non-existing files and directories to the pertinent “index.php” file.
Given the endless possibilities that the mod_rewrite module offers, it’s feasible to add more complex rules to this file to make it more flexible and efficient. For the moment, however, I’m going to keep it that simple, so you can focus your attention on the components of the framework that I’m going to create in just a bit.
Well, at this point the first objective for the development of the framework has been successfully accomplished, since the above .htaccess file will redirect all of the requests made by users to “index.php.” Of course, it’s up to you to choose the directory where this file will reside, but make sure that the configuration of Apache will accept directives from .htaccess files for that particular folder or virtual host.
Now that this initial .htaccess file has been properly created, I'm going to define the aforementioned “index.php” file, which will comprise the framework’s front controller.
This file will perform some simple but useful tasks. To learn how it will be defined, jump ahead and read the following section. It’s only one click away.