2016-11-09 93 views
1

我想从Slim框架中定义的路由生成一个动态的下拉菜单,这里是我的问题 - 有没有办法从某种数组访问所有定义的静态路由?如何从Slim 3 php框架访问所有路线?

举例来说,如果我定义我的路线是这样的:

// 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> 

每当我改变定义的路线,我希望这个菜单随它改变。有没有办法做到这一点?

回答

5

快速搜索Router class in GitHub project for Slim会显示一个公共方法getRoutes(),它返回$this->routes[]路由对象数组。从路由对象,你可以使用getPattern()方法得到的路由模式:

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

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

编辑:新增例如

+0

但它返回一堆'Route' [对象](https://github.com/slimphp/Slim/blob/3.x/Slim/Route.php),这可能不是OP的需要。 –

+1

@GeorgyIvanov是的,但您可以在迭代阵列时挑选要打印的每个对象内的属性。 – Wolf

+0

这似乎是我想要的。谢谢沃尔夫!我已经在所有页面加载了“require_once”之后,在PHP文件中放置'$ container ['allRoutes'] = $ app-> getContainer() - > router-> getRoutes();'然后使用从页面内$ path = $ this-> allRoutes;'。这种方法好吗? –

2

是的。您可以在Slim中使用name your routes。这是一个非常简单的方式完成:用占位符

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

可以命名路线太:

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

现在,你可以通过名字像这样得到URL

// 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' 

这肯定是要走的路,因为如果您通过模板中的名称引用路由,那么如果您需要更改网址,则只需在路由定义中执行此操作。我觉得这个特别酷。

0

基于狼的回答,我已经做了我的解决方案。

在您定义路线的页面中,在它们下面我们将使用我们定义的路线创建一个容器。

// 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 
    ... 
) 

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

+0

它可以与占位符一起工作吗? –

+1

它不会。只有静态路由。 –

+0

它也值得得到'$ route-> getMethods()'的数据来知道路由是否是'GET' /'POST'等 – user3791372