Skip to content

Instantly share code, notes, and snippets.

@zenril
Created July 28, 2015 05:53
Show Gist options
  • Save zenril/b1827e588f256281bd4c to your computer and use it in GitHub Desktop.
Save zenril/b1827e588f256281bd4c to your computer and use it in GitHub Desktop.
Advanced router
<?php
namespace MToolBox\Core;
use Exception;
class Routes {
public $routes;
public $all;
function Routes( ) {
$this->routes = array();
$this->all = array();
//add_filter( 'init' , array( &$this , 'request_parser' ) );
}
public function rule($method,$name,$rule,$func_ref){
//change to uppercase as its uses as a key and need to keep consistant
$method = strtoupper($method);
// make sure an array for the method exists
if(!isset($this->routes[$method])){
$this->routes[$method] = array();
}
/*
Replace the url format with correct
regex format to retrieve named objects from the url
*/
$pattern = '|\:([^\/]*)|';
$replacement = '(?P<${1}>[^/]*)';
$formatted_rule = preg_replace($pattern, $replacement, $rule);
//$formatted_rule = preg_replace('/\//', '\/', $formatted_rule);
//**** dun dun dun, add the new rule ****//
$this->all[$name] = (object) array(
'method' => $method,
'name' => $name,
'formatted_rule' => $formatted_rule,
'rule' => $rule,
'func_ref' => $func_ref
);
$this->routes[$method][] = $this->all[$name];
self::parseRule($this->all[$name]);
}
public static function parseRule($rule) {
$toParse = $_SERVER["REQUEST_URI"];
/* Find set of routes based
on REQUEST_METHOD :
So it limits the number of
regex search having to be done. */
$reqMethod = strtoupper($_SERVER['REQUEST_METHOD']);
if(!in_array($rule->method, array("GET", "ANY") )){
return;
}
//$routesRules = $this->routes[$routesRules];
if(!is_callable($rule->func_ref)){
continue;
}
preg_match('|' . $rule->formatted_rule. '|', $toParse, $params);
if( count($params) > 0 ){
call_user_func($rule->func_ref, $params);
break;
}
}
}
class View {
public static function JSON($any){
header('Content-Type: application/json');
echo json_encode($any);
exit;
}
public static function load($themerelativepath, $data ,$content_type = null){
if(empty($content_type)){
header('Content-Type: '.$content_type);
}
foreach ($data as $key => $value) {
if(isset($GLOBALS[$key])){
throw new Exception($key. ' already exists in the global variables, cannot include "'.get_stylesheet_directory().'\\'.$themerelativepath.'"');
// var_dump($E);
exit;
}
$GLOBALS[$key] = $value;
}
include(get_stylesheet_directory().'/'.$themerelativepath);
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment