123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- <?php
- require_once('path.class.php');
- require_once('response.class.php');
- class Router {
- private $_paths = array();
- private $_base = '/';
- private $responses = array();
- public function __construct($base = null, $paths = null){
- if($paths != null){
- $this->paths($paths);
- }
- if($base != null){
- $this->base($base);
- }
- }
- public function __get($name){
- switch($name){
- case 'base':
- return $this->_base;
- break;
- }
- }
- public function __clone(){
-
- }
- public function __destruct(){
- $this->_paths = array();
- }
- public function __toString(){
- return "[Router]";
- }
- public function base($base){
- $this->_base = $base;
- }
- public function url($url){
- return preg_replace('/(\/+)/','/',$url);
- }
-
- public function path($path,$fn){
- $obj = false;
- foreach($this->_paths as $k => $p){
- if($p->path == $path){
- $obj = $p;
- }
- }
- if(!$obj){
- $obj = new Path($path);
- array_push($this->_paths,$obj);
- }
- return $obj->handle($fn);
- }
- public function paths($paths){
- foreach($paths as $path => $fn){
- $this->path($path,$fn);
- }
- }
- public function clear(){
- $this->_paths = array();
- }
- public function handle($url,$res = null,$fn = null,$onerror = null){
- if($url[0] != '/'){
- $url = '/'.$url;
- }
- if(is_null($res)){
- $res = new Response($url);
- }else{
- $res->url = $url;
- }
- if(!in_array($res,$this->responses)){
- array_push($this->responses,$res);
- }
- ob_start();
- $handled = false;
- foreach($this->_paths as $k => $p){
- if($p->matches($url)){
- $handled = true;
- try{
- $p($res,$p->args($url));
- }catch(Exception $e){
- if(!is_null($onerror)){
- $onerror($res,$e);
- }else{
- throw $e;
- }
- }
- }
- }
- if(!$handled && !is_null($fn)){
- $fn($res,$url);
- }
- $res->output = ob_get_contents();
- ob_end_clean();
- return $res;
- }
- }
- ?>
|