用原生PHP寫一個像CodeIgniter的路由功能_PHP教程

來源:互聯網
上載者:User
前段時間寫了個關於手機應用的api,一直是用的query_string這種地址,而且還是根據一個act參數來區分所有的動作,這種讓開發人員看起來比較費眼。本來想改寫為“?c=controller&m=method&type=3&id=1” 這種形式,利用m參數來載入檔案並進行執行個體化,後來看了sina weibo api 是對地址進行了路由。也決定跟風對地址路由。本來CI架構自己內建路由效果,但是因為考慮是寫api,想寫的比較純粹一點。

支援預設控制器(index)和方法(index):

index.phpindex.php/controllerindex.php/controller/methodindex.php/controller/method/prarme1/value1index.php/controller/method/param1/value1/param2/value2.....
';//這裡需要對$SE_STRING進行過濾處理。$ary_url=array(    'controller'=>'index',    'method'=>'index',    'pramers'=>array()    );//var_dump($ary_url);$ary_se=explode('/', $SE_STRING);$se_count=count($ary_se);//路由控制if($se_count==1 and $ary_se[0]!='' ){    $ary_url['controller']=$ary_se[0];}else if($se_count>1){//計算後面的參數,key-value    $ary_url['controller']=$ary_se[0];    $ary_url['method']=$ary_se[1];    if($se_count>2 and $se_count%2!=0){ //沒有形成key-value形式        die('參數錯誤');    }else{        for($i=2;$i < $se_count;$i=$i+2){            $ary_kv_hash=array(strtolower($ary_se[$i])=>$ary_se[$i+1]);            $ary_url[pramers]=array_merge($ary_url[pramers],$ary_kv_hash);        }    }}$module_name=$ary_url['controller'];$module_file=MODULE_DIR.$module_name.'.class.php';//echo $module_file;$method_name=$ary_url['method'];if(file_exists($module_file)){    include($module_file);    $obj_module=new $module_name();    //執行個體化模組m    if(!method_exists($obj_module, $method_name)){        die('方法不存在');    }else{        if(is_callable(array($obj_module, $method_name))){    //該方法是否能被調用            //var_dump($ary_url[pramers]);            $get_return=$obj_module->$method_name($ary_url[pramers]);    //執行a方法,並把key-value參數的數組傳過去            if(!is_null($get_return)){ //傳回值不為空白                var_dump($get_return);            }                    }else{            die('該方法不能被調用');        }            }}else{    die('模組檔案不存在');}?>

http://www.bkjia.com/PHPjc/752353.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752353.htmlTechArticle前段時間寫了個關於手機應用的api,一直是用的query_string這種地址,而且還是根據一個act參數來區分所有的動作,這種讓開發人員看起來比...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.