27

First of all, I'm a beginner to PHP. And have posted a question here: Refactoring require_once file in a project . I've tried to read about Front controller as much as I can, but can't get how it works or even what's all about.

Can somebody explain in brief how it works and what's all about?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Rafael Adel
  • 7,673
  • 25
  • 77
  • 118
  • It's a single point of entry. Every request is handled by the front controller. Have you read http://en.wikipedia.org/wiki/Front_controller ? – Felix Kling Jul 31 '11 at 15:10
  • 1
    Yea, but the link doesn't give me much information about it. How is it done and stuff like that ? – Rafael Adel Jul 31 '11 at 15:15

1 Answers1

48

Front Controller refers to a design pattern where a single component in your application is responsible for handling all requests to other parts of an application. It centralizes common functionality needed by the rest of your application. Templating, routing, and security are common examples of Front Controller functionality. The benefit to using this design pattern is that when the behavior of these functions need to change, only a small part of the application needs to be modified.

In web terms, all requests for a domain are handled by a single point of entry (the front controller).

An extremely simple example of only the routing functionality of a front-controller. Using PHP served by Apache would look something like this. Most important step is to redirect all requests to the front controller:

.htaccess

RewriteEngine On
RewriteRule . /front-controller.php [L]

front-controller.php

<?php

switch ($_SERVER['REQUEST_URI']) {
    case '/help':
        include 'help.php';
        break;
    case '/calendar':
        include 'calendar.php';
        break;
    default:
        include 'notfound.php';
        break;
}
TigerTV.ru
  • 1,058
  • 2
  • 16
  • 34
h0tw1r3
  • 6,618
  • 1
  • 28
  • 34