認真學習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; } }
效果 :