認真學習php物件導向-4

來源:互聯網
上載者:User
認真學習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;        }    }
效果 :

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.