Blogger Information
Blog 32
fans 0
comment 0
visits 22488
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
08-07作业:写一个简单的路由, 将URL地址直接路由一个函数上
Yx的博客
Original
793 people have browsed it

*. 路由的原理与实现:

* 从pathinfo地址切割为独立的数组单元
* 从pathinfo数组中解析出:模块,控制器和操作
* 从pathinfo数组中解析出:参数键值对

demo实例如下:

<?php
//这里将是实现路由分发的网址如下:
//http://php.io/2019/demo1.php/hello/id/6/name/admin

//hello:方法
//id、name:参数
//6、admin:参数值

$uri=$_SERVER['PATH_INFO'];

// 1. 从pathinfo切割出独立的单元

$request=explode('/',$uri);

echo '<pre>'. print_r($request, true);

// 2. 从pathinfo中解析出操作
$pathinfo['action']=$request[1];
echo '<pre>'. print_r($pathinfo, true);

// 3. 从pathinfo中解析出变量键值对
$values = array_slice($request, 2);

$pathinfo['action']=function (...$arr) use( $pathinfo ){

    for($i=0;$i<count($arr);$i+=2){
        if(isset($arr[$i+1])){
            $params[$arr[$i]]=$arr[$i+1];
        }
    }
    $str='';
    foreach ($params as $key=>$value){
        $str.=$key.'='.$value.' ';
    }
    return '方法名:'.$pathinfo['action'].' ,参数: '.$str;
};

echo call_user_func_array($pathinfo['action'],$values);

运行实例 »

点击 "运行实例" 按钮查看在线实例

运行后显示如下:

01.png

Correction status:qualified

Teacher's comments:写得不错, 理解 了原理
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post