Back to Blog
Lesson 30 of the PHP: Modern PHP from the Ground Up course
PHPAugust 17, 20264 min read

The Front Controller Pattern: Centralizing PHP Request Handling

Master the Front Controller pattern to route all application traffic through a single entry point, simplifying your PHP MVC architecture and URL handling.

PHPWeb DevelopmentMVCArchitectureRouting
Close-up of PHP code on a monitor, highlighting development and programming concepts.

Previously in this course, we explored building the controller layer to handle specific application logic. While that moved us toward an MVC structure, we still face a common problem: our URL structure is tied to our file structure. If a user visits /views/user/profile.php, they are accessing the file directly.

The front controller pattern solves this by forcing every incoming request through a single file (usually index.php). This gives you a "chokepoint" to handle security, logging, and routing for your entire application.

The Problem: File-Based Routing

In a traditional PHP setup, the web server looks for a file that matches the URL. If you have a contact.php file, the server executes it when you visit example.com/contact.php. This is brittle; if you want to change your URL structure or hide your directory layout, you can't, because the file system dictates your URLs.

How the Front Controller Works

Detailed view of a green tractor cab with a clear windshield, showcasing modern farm equipment.

A front controller acts as a traffic cop. When a request hits your server, the server is instructed to ignore the requested file path and instead hand every request to index.php.

Inside index.php, you inspect the requested URL (stored in $_SERVER['REQUEST_URI']) and decide which controller and method should handle the logic.

1. Configuring URL Rewriting with .htaccess

To direct all traffic to index.php, we use the web server's rewrite engine. If you are using Apache, you create an .htaccess file in your project root.

APACHE
# .htaccess
RewriteEngine On

# If the request is not for a real file or directory...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# ...send the request to index.php
RewriteRule ^ index.php [QSA,L]
  • RewriteCond %{REQUEST_FILENAME} !-f: Only proceed if the requested path is not an existing file (like a CSS or JS file).
  • RewriteCond %{REQUEST_FILENAME} !-d: Only proceed if the requested path is not an existing directory.
  • RewriteRule ^ index.php [QSA,L]: The ^ matches everything, sending it to index.php. QSA (Query String Append) ensures your URL parameters (like ?id=1) are preserved.

2. Building the Front Controller Dispatcher

Now that all traffic lands in index.php, we need to parse the URL to determine what the user wants.

PHP
#6A9955">// public/index.php
$request = $_SERVER['REQUEST_URI'];

#6A9955">// Strip the query string (e.g., /profile?id=1 becomes /profile)
$path = parse_url($request, PHP_URL_PATH);

#6A9955">// Simple routing logic
switch ($path) {
    case '/':
        echo "Welcome home!";
        break;
    case '/about':
        echo "This is our about page.";
        break;
    default:
        http_response_code(404);
        echo "404 Not Found";
}

By centralizing this logic, you can implement features like authentication checks or global logging in one place, which then applies to every single route in your application.

Hands-on Exercise

  1. Create an .htaccess file in your project root with the configuration provided above.
  2. Create an index.php file in the same directory.
  3. Add a switch statement to index.php that routes three paths: /, /contact, and /dashboard.
  4. Test by visiting these URLs in your browser. Verify that visiting a non-existent path (e.g., /xyz) triggers your default 404 handler.

Common Pitfalls

  • Forgetting to allow assets: If you don't include the RewriteCond lines for -f and -d, your CSS, JS, and images will stop loading because the server will try to run them through index.php instead of serving them as files.
  • Hard-coding logic: Avoid putting business logic inside index.php. Use it only as a "bootstrap" file that loads your configuration and dispatches the request to a controller class.
  • Relative URLs: Once you start using URL rewriting, your relative links (like href="style.css") might break if the user is deep in a virtual URL. Use absolute paths starting from the root (e.g., href="/css/style.css") to avoid this.

Frequently Asked Questions

Does every framework use this? Yes. Laravel, Symfony, and Slim all use a front controller pattern. It is the industry standard for modern PHP applications.

Can I use this without Apache? Yes. If you use Nginx, you would use a try_files directive in your site configuration to achieve the same result as the .htaccess file.

Is it slow to route everything through one file? The performance overhead of a single switch statement or a routing library is negligible compared to the benefits of centralized security and code organization.

Recap

By implementing a front controller, we've decoupled our URL structure from our directory structure. We used .htaccess to redirect traffic and a central index.php to dispatch requests. This setup is the foundation of the MVC architecture we are building.

Up next: We will learn about Namespaces in PHP to keep our growing controller and model classes organized.

Similar Posts