PHP:简单路由类,请问如何添加多条路由

问题描述 投票:0回答:1

我尝试使用一个简单的Router类(在框架之前学习基础知识,但是我认为我使用的示例路由器存在一些问题。下面是我从同事那里得到的一个很小的路由器类,我试图将其集成插入我的代码中,以替换之前使用echo的先前用法(注释掉部分代码)。loginController showLoggedInUser()和registerController index()都仅用于呈现html模板。

如果我仅使用它添加一条路由,$ router-> add()都会起作用,但是我的路由器不会在数组中保存多个路由,因为似乎每条路由都将保存在键'/'下并在如果我提供多条路线,似乎以前的路线只是被覆盖。所以我想我需要调整Router类。我该如何解决?

使用PHP 7.4

Router.php

<?php
declare(strict_types=1);

class Router
{
    private array $route;

    public function add(string $url, callable $method): void
    {
        $this->route[$url] = $method;
    }

    public function run()
    {

        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        if(!array_key_exists($path, $this->route))

        {
            exit();
        }
        return call_user_func($this->route[$path]);
    }
}

index.php

<?php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

session_start();

$router = new Router();

$mysqliConnection = new MysqliConnection();
$session = new SessionService();

$loginController = new Login($mysqliConnection);
$router->add('/', [$loginController, 'showLoggedInUser']);
//echo $loginController->showLoggedInUser();


$registerController = new Register($mysqliConnection);
$router->add('/', [$registerController, 'index']);
//echo $registerController->index();


echo $router->run();
php arrays router
1个回答
0
投票

不确定具有两条相同名称的路由的总体原理,但是您可以使用每个路由的可调用列表来实现这一点。

© www.soinside.com 2019 - 2024. All rights reserved.