Some time ago wrote a mobile phone application API, has been used query_string this address, but also based on an act parameter to distinguish all the action, which makes developers look more cost-sensitive. Originally intended to be rewritten as "? C=controller&m=method&type=3&id=1", the M parameter was used to load the file and instantiate it, and then the Sina Weibo API was routed to the address. Also decided to follow suit to address routing. Originally the CI framework has its own routing effect, but because the consideration is write API, want to write more purely.
Supports default controller (index) and Method (index):
Copy Code code as follows:
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 classes are as follows:
Copy Code code as follows:
<?phpdefine (' Module_dir ', './classes/');
$APP _path= str_replace ($_server[' document_root ', __file__);
$SE _string=str_replace ($APP _path, ', $_server[' Request_uri ')); Calculates the field following the index.php INDEX.PHP/CONTROLLER/METHON/ID/3
$SE _string=trim ($SE _string, '/');
echo $SE _string. ' <br> ';
There is a need to filter the $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);
Routing control
if ($se _count==1 and $ary _se[0]!= ') {
$ary _url[' controller ']= $ary _se[0];
}else if ($se _count>1) {//Computes subsequent arguments, Key-value
$ary _url[' controller ']= $ary _se[0];
$ary _url[' method ']= $ary _se[1];
if ($se _count>2 and $se _count%2!=0) {//no key-value form
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 (); Instantiating 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 invoked
Var_dump ($ary _url[pramers]);
$get _return= $obj _module-> $method _name ($ary _url[pramers]); Executes a method and passes an array of key-value parameters
if (!is_null ($get _return)) {//return value is not NULL
Var_dump ($get _return);
}
}else{
Die (' This method cannot be invoked ');
}
}
}
Else
{
Die (' module file does not exist ');
}
?>