PHP Front Controller Using Functions


This is an extremely simple (only 9 lines), straightforward, easy to read, understand and maintain front controller for PHP, which routes requests to functions (actions).

It uses convention over configuration making life a breeze (see below)

 

PHP Source Code

include 'app/boot.php';

$action = $_SERVER['REQUEST_URI'] == '' ? 'home' : trim($_SERVER['REQUEST_URI']);
$function_name = trim(str_replace(['-'], '_', $action), '/');

@include_once 'app/pages/' . $function_name . '.php';

if (function_exists($function_name.'_action')) {
    die(($function_name.'_action')());
}

// Page not found
include_once 'app/pages/page_not_found.php';
die(page_not_found_action());

 

Conventions Used

1. Every request is redirected to an action file, which responds to the request

2. Every action file contains an action function ending in _action , which will be called

3. Once the action file is called the request is killed

4. The action files are placed in a single folder /app/pages

 

How to use?

The controller will route the requests as follows

Route File Included Function Called
/ /app/pages/home.php home_action()
/contact /app/pages/contact.php contact_action()
/auth/login /app/pages/auth/login.php auth_login_action()
/page-not-found /app/pages/page_not_found.php page_not_found_action()

 

 

 

 

 

All not found requests will be redirected to the page not found action.

Examples

1. Home page

function home_action() {
    return 'Hello world';
}

2. Page not found page

function page_not_found_action() {
    return 'Page not found: ' . $_SERVER['REQUEST_URI'];
}

2. Contact page

function contact_action() {
    if (is('post')) {
        // Validate submtted contact form
        // Send contact notification
        // Redirect        
    }

    return include('contact_form.phtml');
}

 

Extra Helping Functions

Here are some extra functions you may add to your boot.php file.

function is($requestAction) {
    return $_SERVER['REQUEST_METHOD'] == strtoupper(trim($requestAction));
}

function redirect($path){
    header('Location:'.$path);
    exit;
}