Home > php教程 > php手册 > [PHP] Implement route mapping to specified controller

[PHP] Implement route mapping to specified controller

PHP中文网
Release: 2016-08-15 16:49:45
Original
1599 people have browsed it

自定义路由的功能,指定到pathinfo的url上,再次升级之前的脚本

SimpleLoader.php

<?php
class SimpleLoader{
    public static function run($rules=array()){
        header("content-type:text/html;charset=utf-8");
        self::register();
        self::commandLine();
        self::router($rules);
        self::pathInfo();
    }
    //自动加载
    public static function loadClass($class){
        $class=str_replace(&#39;\\&#39;, &#39;/&#39;, $class);
        $dir=str_replace(&#39;\\&#39;, &#39;/&#39;, __DIR__);
        $class=$dir."/".$class.".php";
        if(!file_exists($class)){
            header("HTTP/1.1 404 Not Found");
        }
        require_once $class;        
    }
    //命令行模式
    public static function commandLine(){
        if(php_sapi_name()=="cli"){
            $_SERVER[&#39;PATH_INFO&#39;]="";
            foreach ($_SERVER[&#39;argv&#39;] as $k=>$v) {
                if($k==0) continue;
                $_SERVER[&#39;PATH_INFO&#39;].="/".$v;
            }
        }
    }
    //路由模式
    public static function router($rules){
        if(isset($_SERVER[&#39;PATH_INFO&#39;]) && !empty($rules)){
            $pathInfo=ltrim($_SERVER[&#39;PATH_INFO&#39;],"/");
            foreach ($rules as $k=>$v) {
                $reg="/".$k."/i";
                if(preg_match($reg,$pathInfo)){
                    $res=preg_replace($reg,$v,$pathInfo);
                    $_SERVER[&#39;PATH_INFO&#39;]=&#39;/&#39;.$res;
                }
            }
        }
    }
    //pathinfo处理
    public static function pathInfo(){
        if(isset($_SERVER[&#39;PATH_INFO&#39;])){
            $pathinfo=array_filter(explode("/", $_SERVER[&#39;PATH_INFO&#39;]));
            for($i=1;$i<=count($pathinfo);$i++){
                $key=isset($pathinfo[$i]) ? $pathinfo[$i] : &#39;&#39;;
                $value=isset($pathinfo[$i+1]) ? $pathinfo[$i+1] :"";
                switch ($i) {
                    case 1:
                        $_GET[&#39;m&#39;]=ucfirst($key);
                        break;
                    case 2:
                        $_GET[&#39;c&#39;]=ucfirst($key);
                        break;
                    case 3:
                        $_GET[&#39;a&#39;]=$key;
                        break;
                    default:
                        if($i>3){
                            if($i%2==0){
                                $_GET[$key]=$value;
                            }
                        }
                        break;
                }
            }
        }
        $_GET[&#39;m&#39;]=!empty($_GET[&#39;m&#39;]) ? ucfirst($_GET[&#39;m&#39;]) : &#39;Index&#39;;
        $_GET[&#39;c&#39;]=!empty($_GET[&#39;c&#39;]) ? ucfirst($_GET[&#39;c&#39;]) : &#39;Index&#39;;
        $_GET[&#39;a&#39;]=!empty($_GET[&#39;a&#39;]) ? $_GET[&#39;a&#39;] : &#39;index&#39;;
        $class="\\Controller\\{$_GET[&#39;m&#39;]}\\{$_GET[&#39;c&#39;]}";
        $controller=new $class;
        if(method_exists($controller, $_GET[&#39;a&#39;])){
            $controller=new $class;
            $controller->$_GET[&#39;a&#39;]();
        }else{
            header("HTTP/1.1 404 Not Found");
            echo "404";
        }
    }
    //致命错误回调
    public static function shutdownCallback(){
        $e=error_get_last();
        if(!$e) return;
        self::myErrorHandler($e[&#39;type&#39;],&#39;<font color="red">Fatal Error</font> &#39;.
        $e[&#39;message&#39;],$e[&#39;file&#39;],$e[&#39;line&#39;]);
    }
    //错误处理
    protected static function myErrorHandler($errno,$errstr,$errfile,$errline){
        list($micseconds,$seconds)=explode(" ",microtime());
        $micseconds=round($micseconds*1000);
        $micseconds=strlen($micseconds)==1 ? &#39;0&#39;.$micseconds : $micseconds;
        if(php_sapi_name()=="cli"){
            $break="\r\n";
        }else{
            $break="<br/>";
        }
        $mes="[".date("Y-m-d H:i:s",$seconds).":{$micseconds}] ".$errfile." ".$errline." line ".$errstr.$break;
        echo $mes;        
    }
    //注册
    public static function register(){
        error_reporting(0);
        set_error_handler(function($errno,$errstr,$errfile,$errline){
            self::myErrorHandler($errno,$errstr,$errfile,$errline);
        });
        register_shutdown_function(function(){
            self::shutdownCallback();
        });
        spl_autoload_register("self::loadClass");
    }
}
Copy after login


如何使用

index.php

<?php
//路由映射
$rules=array(
    &#39;^user$&#39;=>&#39;User/User/getUserList&#39;,
    &#39;^user\/(\d+)$&#39;=>&#39;User/User/getUserById/id/$1&#39;,
    &#39;^user\/(\d+)\/article$&#39;=>&#39;User/User/getUserArticle/uid/$1&#39;
);
require_once "SimpleLoader.php";
SimpleLoader::run($rules);
Copy after login

控制器啥样

\Controller\User\User.php

<?php
namespace Controller\User;

class User{
    public function getUserById(){
        echo "用户信息id {$_GET[&#39;id&#39;]} 的信息";
    }
    public function getUserList(){
        echo "用户列表";
    }
    public function getUserArticle(){
        echo "用户id {$_GET[&#39;uid&#39;]} 的文章列表";
    }
}
Copy after login


效果呢:


以上就是[PHP] 实现路由映射到指定控制器的内容,更多相关内容请关注PHP中文网(www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template