我正在尝试从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>每当我改变定义的路线,我希望这个菜单随着它的变化。有办法做到这一点吗?
发布于 2016-11-09 20:48:45
对Slim GitHub项目中的路由器类的快速搜索显示了一个公共方法getRoutes(),它返回路由对象的$this->routes[]数组。从路由对象中,可以使用getPattern()方法获得路由模式:
$routes = $app->getContainer()->router->getRoutes();
// And then iterate over $routes
foreach ($routes as $route) {
echo $route->getPattern(), "<br>";
}编辑:新增示例
发布于 2016-11-09 13:32:31
是。你可以在斯利姆说出你的路线。这是以非常简单的方式完成的:
$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,则只需要在路由防御时进行。我觉得这特别酷。
发布于 2019-05-17 07:59:49
正如我在“苗条”的相应问题中所评论的:
$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));https://stackoverflow.com/questions/40505551
复制相似问题