The Front Controller Design Pattern (using PHP)

The Front Controller Design Pattern (explained using PHP) Table of contents

  1. Redirecting all requests to a single .php file (using Apache)
  2. The front controller (index.php)

    The front controller is a simple to understand design pattern where you have a main controller that handles every request for a website. It is a commonly used design pattern for many MVC based web applications.

    To use the front controller pattern, you need to have a single part of your website that is fully responsible for handling all incoming requests to your site/application. It will often (but not always) work with a routing and templating system to return a relevant response to the request.

    A very basic example of a front controller could be something like this, in PHP (using Apache .htacess redirect rules):

    Redirecting all requests to a single .php file (using Apache)

    For a typical website that uses a front controller, you will normally want to 'redirect' (not with an actual HTTP location redirect) all requests to a single file.

    RewriteCond %{REQUEST_FILENAME} !-f<br>
    RewriteCond %{REQUEST_FILENAME} !-d<br>
    RewriteRule ^([^?]*)$ /index.php [NC,L,QSA]</p>

    The above should be put into a .htaccess file.

    The front controller (index.php)

    In this super basic example, all requests are routed through index.php. This isn't a good example to follow, but shows a front controller at its most basic. It assumes URLs such as http://yoursite.com/?page=blog, http://yoursite.com/?page=about, etc.

    <?php 
    if (isset($_GET['page'])) {
    $requested_page = $_GET['page'];
    }
    else {
    $requested_page = 'home';
    }
    // a better way would be to put this into an array, but I think a switch is easier to read for this example
    switch($requested_page) {
       case "blog":
          include(__DIR__."/blog.php");
          break;
       case "home":
          include(__DIR__."/home.php");
          break;
       default:
          include(__DIR__."/404.php");
    }

    Of course, in the real world it would be far less simple.

    It is much better to be serving all requests via a front controller (rathe than, in the example above, telling users to go direct to /blog.php) as you can easily make changes in the front controller (index.php, in the example) and apply it to all incoming requests.

    Many frameworks, such as Laravel or Symfony use a (much more complicated!) front controller pattern.

    Comments The Front Controller Design Pattern (using PHP)