<?php
/**
* URL CHECK ROUTER
*
* @author UralKid ([email protected])
* @version 1.0
*
*/
class Router {
/**
* Массив маршрутов
*
* @var array
*/
public $map = array();
/**
* Массив
*
* @var unknown_type
*/
public $route = array();
/**
* запрошенный маршрут
*
* @var unknown_type
*/
public $request = '';
/**
* рега
*
* @var unknown_type
*/
public $regex = '';
const PERMIT = 0;
const DENIED = 1;
public function __construct($routes,$request){
if(is_array($routes)){
$this->map = $routes;
$this->request = $request;
} else {
throw new Exception('not is valid a routes');
}
}
public function process(){
if($this->request){
if($this->match()){
return array(self::PERMIT,$this->GetRoute());
}else {
return array(self::DENIED,$this->request);
}
}
return;
}
public function SetRoute($arg = array()) {
$this->route[$arg[0]] = $arg[1];
}
public function GetRoute(){
return $this->route;
}
public function match(){
foreach ($this->map as $key=>$val){
$this->regex = '#^'.$key.'$#i';
if(preg_match($this->regex,$this->request,$matches) ) {
foreach ($val as $k=>$v){
if(!strstr($v,'$')){
$this->setRoute(array($k,$v));
}else {
$num = substr(strstr($v,'$'),1);
$this->setRoute(array($k,$matches[$num]));
}
}
return true;
}
}
return false;
}
}
?>
Пример использования:
class request {
public $uri;
public function Get(){
$this->uri = $this->uri = preg_replace("/\/+/",'/',$_SERVER['REQUEST_URI']);
$this->uri = trim($this->uri,'/');
return $this->uri;
}
}
$routes = array(
'blog.html' => array(
'controller' => 'blog',
'action' => 'GetPostAll'
),
'blog/post/([a-z_]+).html' => array(
'controller' =>'blog',
'action'=>'getpostid',
'name' => '$1'
)
);
$request = new request();
$router = new Router($routes,$request->get());
http://bhc/blog/post/php_in_action.html
array
0 => int 0
1 =>
array
'controller' => string 'blog' (length=4)
'action' => string 'getpostid' (length=9)
'name' => string 'php_inaction' (length=12)
Если на выходе у нас NULL то индекс, если массив то смотрим его метку, их две permit/denied и далее уже обрабатываем полученные данные как хотим.