【问题标题】:Multiple routes with the same anonymous callback using Slim Framework使用 Slim 框架具有相同匿名回调的多个路由
【发布时间】:2012-07-16 07:14:14
【问题描述】:

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

$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
});

谢谢。

【问题讨论】:

    标签: php slim


    【解决方案1】:

    回调是委托。所以你可以做这样的事情:

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

    【讨论】:

      【解决方案2】:

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

      $app->get('/:route',function()
      {
          //Do same stuff for both routes
      })->conditions(array("route" => "(first_route|second_route)"));
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 这非常聪明,谢谢。我会等着看是否有特定于框架的解决方案。
        猜你喜欢
        • 1970-01-01
        • 2014-08-27
        • 2017-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-18
        • 2018-01-05
        • 1970-01-01
        相关资源
        最近更新 更多