Skip to content

Instantly share code, notes, and snippets.

@jakerb
Created October 5, 2015 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakerb/d161131e926f9b9fea93 to your computer and use it in GitHub Desktop.
Save jakerb/d161131e926f9b9fea93 to your computer and use it in GitHub Desktop.
Dynamic Routing
<?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