在上一课中,咱们实现了简单的根据 URI 执行某个类的某个方法。可是这种映射没有扩展性,对于一个成熟易用的框架确定是行不通的。那么,咱们能够让 框架的用户 经过自定义这种转换来控制,用 CI 的术语就是 ”路由“。php
1. 路由具体负责作什么的?数组
举个例子,上一课中 http://localhost/learn-ci/index.php/welcome/hello, 会执行 Welcome类的 hello 方法,可是用户可能会去想去执行一个叫 welcome 的函数,并传递 'hello' 为参数。框架
更实际一点的例子,好比你是一个产品展现网站, 你可能想要以以下 URI 的形式来展现你的产品,那么确定就须要从新定义这种映射关系了。函数
example.com/product/1/
example.com/product/2/
example.com/product/3/
example.com/product/4/测试
2. 实现一个简单的路由网站
1) 新建 routes.php 文件,并在里面定义一个 routes 数组,routes 数组的键值对即表示路由映射。好比spa
1 /** 2 * routes.php 自定义路由 3 */ 4 5 $routes['default_controller'] = 'home'; 6 7 $routes['welcome/hello'] = 'welcome/saysomething/hello';
2) 在 index.php 中包含 routes.phpcode
1 include('routes.php');
3) 两个路由函数,分析路由 parse_routes ,以及映射到具体的方法上去 set_requestblog
1 function parse_routes() { 2 global $uri_segments, $routes, $rsegments; 3 4 $uri = implode('/', $uri_segments); 5 6 if (isset($routes[$uri])) { 7 $rsegments = explode('/', $routes[$uri]); 8 9 return set_request($rsegments); 10 } 11 } 12 13 function set_request($segments = array()) { 14 global $class, $method; 15 16 $class = $segments[0]; 17 18 if (isset($segments[1])) { 19 $method = $segments[1]; 20 } else { 21 $method = 'index'; 22 } 23 }
4) 分析路由,执行路由后的函数,经过 call_user_func_array() 函数ci
1 parse_routes(); 2 3 $CI = new $class(); 4 5 call_user_func_array(array(&$CI, $method), array_slice($rsegments, 2));
5) 给 Welcome 类添加 saysomething 函数作测试
1 class Welcome { 2 3 function hello() { 4 echo 'My first Php Framework!'; 5 } 6 7 function saysomething($str) { 8 echo $str.", I'am the php framework you created!"; 9 } 10 }
测试结果: 访问 http://localhost/learn-ci/index.php/welcome/hello ,能够看到与第一课不一样的输出结果
hello, I'am the php framework you created!