一步一步重写 CodeIgniter 框架 (2) —— 实现简单的路由功能

在上一课中,我们实现了简单的根据 URI 执行某个类的某个方法。但是这种映射没有扩展性,对于一个成熟易用的框架肯定是行不通的。那么,我们可以让 框架的用户 通过自定义这种转换来控制,用 CI 的术语就是 ”路由“。

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 数组的键值对即表示路由映射。比如

1 /**
2  * routes.php 自定义路由
3  */
4 
5 $routes['default_controller'] = 'home';
6 
7 $routes['welcome/hello'] = 'welcome/saysomething/hello';

  2) 在 index.php 中包含 routes.php

1 include('routes.php');

  3) 两个路由函数,分析路由 parse_routes ,以及映射到具体的方法上去 set_request

 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() 函数

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!

原文地址:https://www.cnblogs.com/zhenyu-whu/p/3166284.html