如何从 Slim 3 php 框架访问所有路由?

How to access all routes from Slim 3 php framework?

我正在尝试从 Slim 框架中定义的路由构建一个动态下拉菜单,这是我的问题 - 有没有办法从某种数组访问所有定义的静态路由?

例如,如果我这样定义我的路线:

// Index page: '/'
require_once('pages/main.php');

// Example page: '/hello'
require_once('pages/hello.php');

// Example page: '/hello/world'
require_once('pages/hello/world.php');

// Contact page: '/contact'
require_once('pages/contact.php');

每个文件都是一个单独的页面,如下所示

// Index page
$app->get('/', function ($request, $response, $args) {

    // Some code

})->setName('index');

我想从某种数组访问所有这些定义的路由,然后使用该数组在我的模板文件中创建一个无序的 HTML 列表。

<ul>
  <li><a href="/">Index</a></li>
  <li><a href="/hello">Hello</a>
    <ul>
       <li><a href="/hello/world">World</a></li>
    </ul>
  </li>
  <li><a href="/contact">Contact</a></li>
</ul>

每当我改变定义的路线时,我希望这个菜单随之改变。有办法实现吗?

是的。您可以在 Slim 中 name your routes。这是以非常简单的方式完成的:

$app->get('/hello', function($request, $response) {
    // Processing request...
})->setName('helloPage'); // setting unique name for route

现在您可以通过这样的名称获得 URL:

$url = $app->getContainer()->get('router')->pathFor('helloPage');
echo $url; // Outputs '/hello'

您也可以使用占位符命名路由:

// Let's define route with placeholder
$app->get('/user-profile/{userId:[0-9]+}', function($request, $response) {
    // Processing request...
})->setName('userProfilePage');

// Now get the url. Note that we're passing an array with placeholder and its value to `pathFor`
$url = $app->getContainer()->get('router')->pathFor('helloPage', ['userId': 123]);
echo $url; // Outputs '/user-profile/123'

这是确定的方法,因为如果您在模板中通过名称引用路由,那么如果您需要更改 URL,您只需在路由定义中进行。我觉得这个特别酷。

快速搜索 Router class in GitHub project for Slim 显示 public 方法 getRoutes(),其中 returns $this->routes[] 路由对象数组。从路由对象中,您可以使用 getPattern() 方法获取路由模式:

$routes = $app->getContainer()->router->getRoutes();
// And then iterate over $routes

foreach ($routes as $route) {
    echo $route->getPattern(), "<br>";
}

编辑:添加示例

根据Wolf的回答,我做出了我的解决方案。

在您定义路由的页面中,我们将在所有路由下方创建一个包含我们定义的路由的容器。

// Get ALL routes
// --------------
$allRoutes = [];
$routes = $app->getContainer()->router->getRoutes();

foreach ($routes as $route) {
  array_push($allRoutes, $route->getPattern());
}

$container['allRoutes'] = $allRoutes;

这将创建一个数组,其中包含我们稍后可以在项目中使用的所需路由。

然后在您定义的路由中,您可以这样调用它:

$app->get('/helloWorld', function ($request, $response, $args) {

  print_r ($this->allRoutes);

})->setName('helloWorld');

这将输出

Array
(
    [0] => /
    [1] => /helloWorld
    [2] => /someOtherRoute
    ...
)

这样我们就可以使用这个数组来创建我们想要的任何东西。再次感谢狼!

正如我在 slim 的相应 issue 中评论的那样:

$routes = array_reduce($this->app->getContainer()->get('router')->getRoutes(), function ($target, $route) {
    $target[$route->getPattern()] = [
        'methods' => json_encode($route->getMethods()),
        'callable' => $route->getCallable(),
        'middlewares' => json_encode($route->getMiddleware()),
        'pattern' => $route->getPattern(),
    ];
    return $target;
}, []);
die(print_r($routes, true));