Heim  >  Artikel  >  Backend-Entwicklung  >  用原生PHP写一个像CodeIgniter的路由功能_PHP教程

用原生PHP写一个像CodeIgniter的路由功能_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:34:02711Durchsuche

前段时间写了个关于手机应用的api,一直是用的query_string这种地址,而且还是根据一个act参数来区分所有的动作,这种让开发人员看起来比较费眼。本来想改写为“?c=controller&m=method&type=3&id=1” 这种形式,利用m参数来载入文件并进行实例化,后来看了sina weibo api 是对地址进行了路由。也决定跟风对地址路由。本来CI框架自己自带路由效果,但是因为考虑是写api,想写的比较纯粹一点。

支持默认控制器(index)和方法(index):

index.php
index.php/controller
index.php/controller/method
index.php/controller/method/prarme1/value1
index.php/controller/method/param1/value1/param2/value2.....
<?php

define('MODULE_DIR', './classes/');
$APP_PATH= str_replace($_SERVER['DOCUMENT_ROOT'], '', __FILE__);    
$SE_STRING=str_replace($APP_PATH, '', $_SERVER['REQUEST_URI']);    //计算出index.php后面的字段 index.php/controller/methon/id/3
$SE_STRING=trim($SE_STRING,'/');
//echo $SE_STRING.'<br>';
//这里需要对$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('模块文件不存在');
}

?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/752353.htmlTechArticle前段时间写了个关于手机应用的api,一直是用的query_string这种地址,而且还是根据一个act参数来区分所有的动作,这种让开发人员看起来比...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn