认真学习php面向对象-4
前言
准备写一个认真学习php面向对象的系列,使用php来做网页,没有深入了解php的话,可能三板斧就够了,并不需要有多高深!如有错误,欢迎各位不吝赐教!进度安排的话,我学到哪里,就更新到哪里了!形式的话就采用一个需求小案例,然后实现,并附上自己的总结,文章源码
需求 :1)模拟生成路由资源文件
我们经常使用框架的时候经常会接触到路由这个概念,今天我们就来模拟简单的路由资源文件的创建,探讨路由资源文件是怎么生成的。
解决 : get_declared_classes(),_CLASS_,array_search以及反射ReflectionClass,getDocComment的使用
上述函数不懂可以在官网寻找其用法
创建index.php
god_frame.php
//获取所有已加载的所有类
$class_set=get_declared_classes();
$class_set=array_slice($class_set,array_search(__CLASS__,$class_set)+1);
$result=array();
foreach ($class_set as $class) {
$mvc=new god_mvc($class);
if($mvc->isController()) {
$mp=$mvc->getRequestMappings();
$result=array_merge($result,$mp);
}
}
//生成路由文件
file_put_contents($this->project_folder.'/request_route','<?php return '.var_export($result,1).';');
新增类god_mvc.php
<?php
namespace core\frame;
class god_mvc
{
public $classComment="";
public $classMethods=array();
public $className="";
function __construct($cname)
{
$this->className=$cname;
$Rf=new \ReflectionClass(($cname));
$this->classComment=$Rf->getDocComment();//获取类的注释
$this->classMethods=$Rf->getMethods();//获取类里面的所有方法集合,返回一个方法对象数组
}
function isController()
{
return preg_match("/@Controller/",$this->classComment);
}
function getRequestMappings()
{
$result=array();
foreach ($this->classMethods as $method) {
$get_res=$this->getRequestMappingsResult($method);
if($get_res){
$result=array_merge($result,$get_res);
}
}
return $result;
}
function getRequestMappingsResult($m) {
if (preg_match('/@RequestMapping\("(?<RequestUrl>.{3,20})",Method=(?<RequestMethod>\w{3,8})\)/',$m->getDocComment(),$result)) {
return array(
$result['RequestUrl']=>array(
'RequestMethod'=>$result['RequestMethod'],
'Class'=>$this->className,
'Method'=>$m->getName()
)
);
}
return false;
}
}