Created
August 27, 2013 16:00
-
-
Save mwalters/6355508 to your computer and use it in GitHub Desktop.
Snippet: Poor Mans PHP Routing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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