PHP: The Ninja Controller

That's right, a ninja controller. It lurks in the shadows and strikes first on each request. The ninja travels with few supplies. This example is under 50 lines. This very simple concept should dramatically decrease the amount of repetitive code in your next PHP app.

The idea is to funnel all requests for php pages through a single file. This master controller file should include the necessary headers and setup for your application. Ideally it will auto-load classes from the file system so you don't have inane include statements all over the place.

It all starts in the .htaccess file. Make your file like so:

RewriteEngine on
RewriteRule (.*)\.php _init.php

Then your _init.php file (the controller file):

<?php

class Car
{
public function getWheels()
{
return 4;
}

public function getPassengers()
{
return mt_rand(0, 4);
}
}

$target = preg_replace('|^' . dirname($_SERVER['SCRIPT_NAME']) . '[/]?|', '', $_SERVER['REQUEST_URI']);
$target = preg_replace('/[?].+$/', '', $target);
if (!$target) {
$target = 'index.php';
}

if (!file_exists($target)) {
throw new Exception("that page does not exist");
}

include $target;

?>

A default page (index.php):

<?php

$car = new Car();

?>

<p>My car has <?php echo $car->getWheels(); ?> wheels.</p>

<a href="page2.php">try page2</a>

And finally one more test page (page2.php):

<?php

$car = new Car();

?>

<p>and I have <?php echo $car->getPassengers(); ?> passengers.</p>

That's it - The Ninja Controller. Download the source here. This source is released under a public domain license.

Offices

Contacts