12

如何定义使用相同匿名回调的多个路由?

$app->get('/first_route',function()
{
   //Do stuff
});
$app->get('/second_route',function()
{
   //Do same stuff
});

我知道我可以使用对可以工作的函数的引用,但我更喜欢使用匿名函数的解决方案以与代码库的其余部分保持一致。

所以基本上,我正在寻找的是一种做这样的事情的方法:

$app->get(['/first_route','/second_route'],function()
{
       //Do same stuff for both routes
});

〜或〜

$app->get('/first_route',function() use($app)
{
   $app->get('/second_route');//Without redirect
});

谢谢你。

4

3 回答 3

20

您可以使用条件来实现这一点。我们用它来翻译 URL。

$app->get('/:route',function()
{
    //Do same stuff for both routes
})->conditions(array("route" => "(first_route|second_route)"));
于 2013-04-02T18:54:23.550 回答
14

我无法为您提供特定于框架的解决方案,但如果有帮助,您可以参考匿名函数:

$app->get('/first_route', $ref = function()
{
   //Do stuff
});
$app->get('/second_route', $ref);
于 2012-07-17T11:19:31.503 回答
4

回调是代表。所以你可以做这样的事情:

$app->get('/first_route', myCallBack);
$app->get('/second_route', myCallBack);

function myCallBack() {
    //Do stuff
}
于 2014-04-18T09:42:52.933 回答