Created
October 5, 2015 14:43
-
-
Save jakerb/d161131e926f9b9fea93 to your computer and use it in GitHub Desktop.
Dynamic 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 | |
/* | |
* @name Dynamic routing for PHP | |
* @author Jake Bown | |
* @edited 05/10/2015 | |
* @info Set up a routing path based on a class, then use the functions as the path string (/model/view/controller). | |
* If you add a colon (:) after the URL, it will be passed as variable to the function. | |
*/ | |
class routing { | |
function path($url) { | |
$paths = explode('/', $url); | |
if(is_array($paths)) { | |
$count = 0; | |
$this->paths = ["path" => $url]; | |
foreach($paths as $path) { | |
if($path) { | |
$count++; | |
$this->paths["paths"][] = $path; | |
if(substr($path, 0, 1) == ":") { | |
$this->variables[$count-1] = substr($path, 1, strlen($path)); | |
} | |
} | |
} | |
$this->paths["count"] = $count; | |
$this->callClass($this->setPaths["paths"]); | |
} | |
} | |
function setClass($class) { | |
$this->class = $class; | |
} | |
function callClass($arr) { | |
$class = new $this->class(); | |
$count = 0; | |
foreach($arr as $path) { | |
if(isset($this->variables[$count])) { | |
$class->$path($this->variables[$count]); | |
} | |
$class->$path(); | |
$count++; | |
} | |
} | |
function setPath($str) { | |
if(isset($this->class)) { | |
$paths = explode('/', $str); | |
$this->setPaths = ["path" => $str]; | |
$count = 0; | |
foreach($paths as $path) { | |
if($path) { | |
$count++; | |
$this->setPaths["paths"][] = $path; | |
} | |
} | |
} | |
} | |
} | |
class phones { | |
/* Based on the dynamic routing, the following | |
* functions are being used in the path. | |
*/ | |
function __construct() { | |
echo "<ul>"; | |
} | |
function company($name = false) { | |
if($name) { | |
echo "<li>Company: $name</li>"; | |
} | |
} | |
function product($name = false) { | |
if($name) { | |
echo "<li>Product: $name</li>"; | |
} | |
} | |
function model($name = false) { | |
if($name) { | |
echo "<li>Model: $name</li>"; | |
} | |
} | |
function version($name = false) { | |
if($name) { | |
echo "<li>Version: $name</li>"; | |
} | |
} | |
function _destruct() { | |
echo "</ul>"; | |
} | |
} | |
$x = new routing(); | |
$x->setClass('phones'); //Use the phones class. | |
$x->setPath('/company/product/model/version'); //Set the path string based on the functions. | |
$x->path('/:Apple/:iPhone/:5/'); //Pass variables into the above function structure. | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment