认真学习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!');
}
}
}