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

时间:2023-03-09 03:59:06
一步一步重写 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 数组的键值对即表示路由映射。比如

 /**
* routes.php 自定义路由
*/ $routes['default_controller'] = 'home'; $routes['welcome/hello'] = 'welcome/saysomething/hello';

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

 include('routes.php');

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

 function parse_routes() {
global $uri_segments, $routes, $rsegments; $uri = implode('/', $uri_segments); if (isset($routes[$uri])) {
$rsegments = explode('/', $routes[$uri]); return set_request($rsegments);
}
} function set_request($segments = array()) {
global $class, $method; $class = $segments[0]; if (isset($segments[1])) {
$method = $segments[1];
} else {
$method = 'index';
}
}

4) 分析路由,执行路由后的函数,通过 call_user_func_array() 函数

 parse_routes();

 $CI = new $class();

 call_user_func_array(array(&$CI, $method), array_slice($rsegments, 2));

5) 给 Welcome 类添加 saysomething 函数做测试

 class Welcome {

     function hello() {
echo 'My first Php Framework!';
} function saysomething($str) {
echo $str.", I'am the php framework you created!";
}
}

测试结果: 访问 http://localhost/learn-ci/index.php/welcome/hello ,可以看到与第一课不同的输出结果

hello, I'am the php framework you created!