PHP URL routing class instance

  • 2020-11-18 06:08:20
  • OfStack

Some time ago, I wrote about api for mobile applications. 1 is the address of query_string, and it can distinguish all actions according to one act parameter, which makes developers look rather expensive. I was going to rewrite it as "? c=controller & m=method & type=3 & id=1 "in this form, the m parameter is used to load the file and instantiate it. Later I saw that sina weibo api is routing the address. Also decided to follow suit and route addresses. Originally, CI framework has its own routing effect, but because it is considered to write api, I want to write a pure 1 point.
Support default controller (index) and method (index) :


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

The specific categories are as follows:


<?phpdefine('MODULE_DIR', './classes/');
$APP_PATH= str_replace($_SERVER['DOCUMENT_ROOT'], '', __FILE__);    
$SE_STRING=str_replace($APP_PATH, '', $_SERVER['REQUEST_URI']);    // To calculate the index.php Following field  index.php/controller/methon/id/3
$SE_STRING=trim($SE_STRING,'/');
//echo $SE_STRING.'<br>';
// So we need to have $SE_STRING Do the filtering process. 
$ary_url=array(
    'controller'=>'index',
    'method'=>'index',
    'pramers'=>array()
    );
//var_dump($ary_url);
$ary_se=explode('/', $SE_STRING);
$se_count=count($ary_se);
// Routing control 
if($se_count==1 and $ary_se[0]!='' ){
    $ary_url['controller']=$ary_se[0];
}else if($se_count>1){// Calculate the following parameters, key-value
    $ary_url['controller']=$ary_se[0];
    $ary_url['method']=$ary_se[1];
    if($se_count>2 and $se_count%2!=0){ // There is no form key-value In the form of 
        die(' Parameter error ');
    }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();    // Instantiate module m
    if(!method_exists($obj_module, $method_name)){
        die(' Method does not exist ');
    }else{
        if(is_callable(array($obj_module, $method_name))){    // Whether the method can be called 
            //var_dump($ary_url[pramers]);
            $get_return=$obj_module->$method_name($ary_url[pramers]);    // perform a methods , And the key-value An array of parameters is passed 
            if(!is_null($get_return)){ // The return value is not null 
                var_dump($get_return);
            }

        }else{
            die(' The method cannot be called ');
        }

    }
}
else
{
    die(' The module file does not exist ');
}
?>


Related articles: