Some time ago, I wrote an api about the mobile app, which always uses the query_string address and distinguishes all the actions based on an act parameter, which makes the developer seem eye-catching. I wanted to rewrite it as "? C = controller & m = method & type = 3 & id = 1 ". The m parameter is used to load and instantiate the file, then we can see that the sina weibo api routes the address. It also decided to follow suit to address routing. Originally, the CI framework had its own routing effect, but because it was considered to be an api, it wanted to write purely.
The default controller (index) and method (index) are supported ):
Copy codeThe Code is 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 codeThe Code is as follows:
<? Phpdefine ('module _ dir', './classes /');
$ APP_PATH = str_replace ($ _ SERVER ['document _ root'], '', _ FILE __);
$ SE_STRING = str_replace ($ APP_PATH, '', $ _ SERVER ['request _ URI ']); // calculate the index. index of the field after php. php/controller/methon/id/3
$ SE_STRING = trim ($ SE_STRING ,'/');
// Echo $ SE_STRING. '<br> ';
// Filter $ 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 );
// Route control
If ($ se_count = 1 and $ ary_se [0]! = ''){
$ Ary_url ['controller'] = $ ary_se [0];
} Else if ($ se_count> 1) {// calculate the following parameter, 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 format is formed
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) {// can this method be called?
// Var_dump ($ ary_url [pramers]);
$ Get_return = $ obj_module-> $ method_name ($ ary_url [pramers]); // execute method a and pass the array of the key-value parameter
If (! Is_null ($ get_return) {// the return value is not empty.
Var_dump ($ get_return );
}
} Else {
Die ('this method cannot be called ');
}
}
}
Else
{
Die ('module file does not exist ');
}
?>