Skip to content

Instantly share code, notes, and snippets.

@mwalters
Created August 27, 2013 16:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwalters/6355508 to your computer and use it in GitHub Desktop.
Save mwalters/6355508 to your computer and use it in GitHub Desktop.
Snippet: Poor Mans PHP Routing
<?php
// CONFIG: Path to Controllers, including trailing slash
$contollerPath = './Controllers/';
// If there is a query string, then get its position so it can be separated from the Controller/Method requested
if (strpos($_SERVER['REQUEST_URI'], '?')) {
$queryOffset = strpos($_SERVER['REQUEST_URI'], '?') - ($_SERVER['REQUEST_URI'] + 1);
} else {
$queryOffset = strlen($_SERVER['REQUEST_URI']);
}
// Parse the Route into an array
$route = substr($_SERVER['REQUEST_URI'], 1, ($queryOffset));
$route = explode('/', $route);
// Obtain the Controller and Method requested
$controller = $route[0];
$controllerMethod = $route[1];
if (file_exists($contollerPath . $controller . '.php')) { // If the Controller file exists
require_once($contollerPath . $controller . '.php'); // Include the Controller file
if (class_exists($controller)) { // If the Controller Class exists
$tmpObject = new $controller; // Instantiate the Controller
if (is_callable(array($tmpObject, $controllerMethod))) { // If the Method is able to be called
call_user_func(array($tmpObject, $controllerMethod)); // Call the Method
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment