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

本文介绍了一个简单的PHP框架中路由机制的实现过程。通过定义自定义路由规则,可以灵活地将URL映射到特定的控制器方法上,提高了框架的灵活性和扩展性。

 

在上一课中,我们实现了简单的根据 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://my.oschina.net/yomut/blog/712590

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值