路由 php mvc

Routing php mvc

例如,当我在 href 中输入路由时,我需要有关路由器的帮助

  • 登录
  • 注册
  • 首先link我点击作品 url 是 localhost/account/login

    但是我第二次点击 link url 是 localhost/account/account/register

    function __construct(){
        $arr = require 'application/config/routes.php';
        foreach ($arr as $key => $val) {
            $this->add($key, $val);
        }
    
    }
    
    public function add($route, $params) {
        $route = '#^'.$route.'$#';
        $this->routes[$route] = $params;
    }
    
    public function match() {
        $url = trim($_SERVER['REQUEST_URI'], '/');
        foreach ($this->routes as $route => $params) {
            if (preg_match($route, $url, $matches)) {
                $this->params = $params;
                return true;
            }
        }
        return false;
    }
    
    public function run(){
        if($this->match()){
            $path = 'application\controllers\'.ucfirst($this->params['controller']).'Controller';
            if(class_exists($path)){
              $action = $this->params['action'].'Action';
              if (method_exists($path, $action)){
                    $controller = new $path($this->params);
                    $controller->$action();
              }else{
                View::errorCode(404);
              }
            }else{
               View::errorCode(404);
            }
        }else{
            View::errorCode(404);
        }
    }    
    

    您的 URL 不以 / 开头,因此它们是相对于当前的 URL。请在前面加一个/

    您现在的代码:

    <a href="account/register">Register</a>
    

    改为:

    <a href="/account/register">Register</a>