PHP 8 - 找不到请求的路由 URL

PHP 8 - Routing can't find requested URL

我的 PHP 8 路由有问题。我正在创建我的 MVC“框架”以了解有关 OOP 的更多信息。我做了路由、控制器和视图 - 它有效,我很高兴。但是我发现我会测试我的创作。这就是问题开始的地方,即如果路径为空(“”),它 return 是路由中要求的“主页”视图,但是如果我在 URL,例如,我有一条 return 消息“404 未找到 - 在此服务器上未找到请求的 URL。”即使给定的路由已添加到 table。怎么了?

.htaccess 文件

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.+)$ index.php [QSA,L]

index.php 路线

<?php

/*
 * Require Composer
 */
require dirname(__DIR__) . '/vendor/autoload.php'; 

/*
 * Routing
 */

$routes = new Core\Router();

$routes->new('', ['controller' => 'HomeController', 'method' => 'index']);
$routes->new('/test', ['controller' => 'HomeController', 'method' => 'test']);

$routes->redirectToController($_SERVER['QUERY_STRING']);

Router.php 文件

<?php

namespace Core;

class Router
{

    /*
     * Routes and parameters array
     */
    protected $routes = [];
    protected $params = [];


    /*
     * Add a route to the route board
     */
    public function new($route, $params = [])
    {
        /* 
         * Converting routes strings to regular expressions 
         */
        $route = preg_replace('/\//', '\/', $route);
        $route = preg_replace('/\{([a-z]+)\}/', '(?P<>[a-z-]+)', $route);
        $route = '/^' . $route . '$/i';

        $this->routes[$route] = $params;
    }


    /*
     * Get all routes from table
     */
    public function getRoutesTable() {
        return $this->routes;
    }


    /*
     * Checking if the specified path exists in the route table
     * and completing the parameters table
     */
    public function match($url)
    {

        foreach($this->routes as $route => $params) {
            
            if(preg_match($route, $url, $matches)) {
                foreach($matches as $key => $match) {
                    if(is_string($key)) {
                        $params[$key] = $match;
                    }
                }

                $this->params = $params;
                return true;
            }
        }

        return false;
    }

    
    /*
     * Get all params from table
     */
    public function getParamsTable() {
        return $this->params;
    }


    /*
     * Redirection to the appropriate controller action
     */
    public function redirectToController($requestUrl) {
        $requestUrl = explode('?', $requestUrl);
        $url = $requestUrl[0];
        
        if ($this->match($url)) {
            $controller = $this->params['controller'];
            $controller = "App\Controllers\$controller";

            if(class_exists($controller)) {
                $controller_obj = new $controller($this->params);
                $method = $this->params['method'];

                if(method_exists($controller, $method)) {
                    $controller_obj->$method();
                } else {
                    echo "Method $method() in controller $controller does not exists!";
                }

            } else {
                echo "Controller $controller not found!";
            }

        } else {
            echo "No routes matched!";
        }
    }
}

View.php 文件

<?php

namespace Core;

class View {
    public static function view($file) {
        $filename = "../App/Views/$file.php";
        
        if(file_exists($filename)) {
            require_once $filename;
        } else {
            echo "View $file is not exist!";
        }
    }
}

家庭控制器文件

<?php

namespace App\Controllers;

use Core\Controller;
use Core\View;

class HomeController extends Controller {
    public function index() {
        return View::view('Home');
    }

    public function test() {
        return View::view('Test');
    }
}

文件夹结构

网络浏览器中的路由

我正在使用 XAMPP 与 PHP 8.0 和 Windows 10。

首先,选择以下两个选项之一继续。

选项 1:

如果文档根目录设置为与项目根目录相同,例如path/to/htdocs,在web服务器的配置文件中(可能是httpd.conf),类似这样:

DocumentRoot "/path/to/htdocs"   
<Directory "/path/to/htdocs">
    AllowOverride All
    Require all granted
</Directory>

然后在 项目根目录 中创建以下 .htaccess,从目录 path/to/htdocs/Public 中删除所有 .htaccess 文件并重新启动 Web 服务器:

<IfModule dir_module>
    DirectoryIndex /Public/index.php /Public/index.html
</IfModule>

Options FollowSymLinks

RewriteEngine On
RewriteBase /Public/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php [QSA,L]

选项 2:

如果文档根目录设置为web服务器配置文件中的目录path/to/htdocs/Public(可能是httpd.conf),类似这样:

DocumentRoot "/path/to/htdocs/Public"   
<Directory "/path/to/htdocs/Public">
    AllowOverride All
    Require all granted
</Directory>

然后在目录 path/to/htdocs/Public 中创建以下 .htaccess,从 项目根目录 中删除任何其他 .htaccess 文件(除非它,也许,包含一些相关设置,而不是 DirectoryIndex) 并重新启动网络服务器::

Options FollowSymLinks

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php [QSA,L]

在您决定并继续执行上述选项之一后,编辑页面 index.php,如下所示:

<?php

//...

/*
 * NOTE: A route pattern can not be an empty string.
 * If only the host is given as URL address, the slash 
 * character (e.g. "/") will be set as value of the
 * URI path, e.g. of $_SERVER['REQUEST_URI']. Therefore, 
 * the route pattern should be set to "/" as well.
 */
$routes->new('/', [
    'controller' => 'HomeController',
    'method' => 'index',
]);

//...

/*
 * In order to get the URI path, you must use the server 
 * parameter "REQUEST_URI" instead of "QUERY_STRING".
 */
$routes->redirectToController(
    $_SERVER['REQUEST_URI']
);

备注:

  • 关于将 $_SERVER['QUERY_STRING'] 更改为 $_SERVER['REQUEST_URI'],当然要归功于@MagnusEriksson。
  • 不能有“MVC 框架”,而是“基于 MVC 的应用程序的 Web 框架” .这是因为框架只是库的集合(与 MVC 完全无关),而这些库又被一个或多个实现 MVC 模式的应用程序使用。

如有任何其他问题,请随时咨询我们。