最新消息:自律使人变得更强大

学习编写PHP框架第二天-路由类

admin 2120 次 0 条

配置项文件

<?php
namespace core\lib;

class config{

    /**
     * 1.判断配置文件是否存在
     * 2.判断配置是否存在
     * 3.将配置缓存
     */
    static public $conf = [];
    static public function get($name,$file){
        if(isset(self::$conf[$file])){
            return self::$conf[$file][$name];
        }else{
            $path = PHPONE.'/core/config/'.$file.'.php';
            if(is_file($path)){
                $conf = include $path;
                if(isset($conf[$name])){
                    self::$conf[$file] = $conf;
                    return $conf[$name];
                }else{
                    throw new \Exception("配置项不存在".$name);    
                }
            }else{
                throw new \Exception("配置文件不存在".$file);    
            }
        }
    }

    static public function getAll($file){
        if(isset(self::$conf[$file])){
            return self::$conf[$file];
        }else{
            $path = PHPONE.'/core/config/'.$file.'.php';
            if(is_file($path)){
                $rs = include $path;
                self::$conf[$file] = $rs;
                return $rs;
            }else{
                throw new \Exception("配置文件不存在".$file);    
            }
        }
    }
}

route.php

<?php
namespace core\lib;
use core\lib\config;

class route{

    public $controller; //控制器
    public $action; //方法

    public function __construct(){
        if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/'){

            //先处理 控制器/方法 controller/action
            $path = $_SERVER['REQUEST_URI'];
            $patharr = explode('/', trim($path,'/'));
            if(isset($patharr[0])){
                $this->controller = $patharr[0];
            }
            unset($patharr[0]);

            if(isset($patharr[1])){
                $this->action = $patharr[1];
                unset($patharr[1]);
            }else{
                $this->action = config::get('action','route');
            }

            //参数部分
            $count = count($patharr) + 2;
            $i = 2;
            while ($i<$count) {
                if(isset($patharr[$i + 1])){
                    $_GET[$patharr[$i]] = $patharr[$i + 1];
                }
                $i = $i + 2;
            }
            
        }else{
            $this->controller = config::get('controller','route');
            $this->action = config::get('action','route');
        }
    }
}
发表我的评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址