認真學習php物件導向-5
前言
準備寫一個認真學習php物件導向的系列,使用php來做網頁,沒有深入瞭解php的話,可能三板斧就夠了,並不需要有多高深。如有錯誤,歡迎各位不吝賜教。進度安排的話,我學到哪裡,就更新到哪裡了。形式的話就採用一個需求小案例,然後實現,並附上自己的總結,文章源碼 需求 :1)類比mvc實現瀏覽器正確訪問
在上一節中我們已經類比產生了路由資源檔,這一節我們根據瀏覽器的正確訪問來載入我們的資源檔。 建立index.php
index.php
$pi=$_SERVER['PATH_INFO'];// $controller=explode('/',$pi)[1];// $method=explode('/',$pi)[2];// require (getcwd().'/code/'.$controller.".class.php");// $get_class=new $controller();// $get_class->$method(); $pi=isset($_SERVER["PATH_INFO"])?$_SERVER["PATH_INFO"]:false; if(!$pi) exit('404'); $route=require ("request_route"); if (array_key_exists($pi,$route)) { $route_obj=$route[$pi]; if ($route_obj['RequestMethod']==$_SERVER['REQUEST_METHOD']) { $className=$route_obj['Class']; $method=$route_obj['Method']; require (getcwd().'/code/'.$className.".class.php"); $class_obj=new $className(); $class_obj->$method(); } else { exit('not allowed!'); } } else { exit('404'); }
效果
訪問存在的路由
訪問不存在的路由
需求 :2)類比mvc url參數注入
在上一節中我們已經類比產生了路由資源檔,這一節我們根據瀏覽器的正確訪問來載入我們的資源檔。 index.class.php
/** * @Controller */class Index{ /** * @RequestMapping("/getseven/(?<name>\w{2,10})",Method=GET) */ public function seven($name) { echo "This is default ".$name; } /** * @RequestMapping("/getage",Method=POST) */ public function shisiying() { echo "This is index"; }}
index.php
function getMatch($v) { return preg_match('/[a-zA-Z]+/',$v); } $pi=$_SERVER['PATH_INFO']; $pi=isset($_SERVER["PATH_INFO"])?$_SERVER["PATH_INFO"]:false; if(!$pi) exit('404'); $route=require ("request_route"); $route_keys=array_keys($route); foreach ($route_keys as $key) { $new_key=str_replace('/','\/',$key); if (preg_match('/'.$new_key.'/',$pi,$result)) { $route_obj=$route[$key]; if ($route_obj['RequestMethod']==$_SERVER['REQUEST_METHOD']) { $className=$route_obj['Class']; $method=$route_obj['Method']; require (getcwd().'/code/'.$className.".class.php"); $params=array_filter($result,'getMatch',ARRAY_FILTER_USE_KEY); $class_obj=new ReflectionClass($className); $getMethod=$class_obj->getMethod($method); if($params && count($params)>0) { $getMethod->invokeArgs($class_obj->newInstance(),$params); } else { $getMethod->invoke($class_obj->newInstance()); } } else { exit('not allowed!'); } } }
效果