【问题标题】:How to bind route with controller with Symfony2 Routing component如何使用 Symfony2 路由组件将路由与控制器绑定
【发布时间】:2014-01-15 22:15:11
【问题描述】:

我想在我的小站点中使用独立的 Symfony2 路由组件。我根据文档和一些示例创建了这个:

$request = Request::createFromGlobals();

$routeTest = new Symfony\Component\Routing\Route('/route-test', array('controller' => 'test'));

$routes = new Symfony\Component\Routing\RouteCollection();
$routes->add('test', $routeTest);

$context = new Symfony\Component\Routing\RequestContext();
$context->fromRequest($request);

$matcher = new Symfony\Component\Routing\Matcher\UrlMatcher($routes, $context);
$matcher->match($request->getPathInfo());

我不明白我应该如何调用我的控制器测试,我已经传递给了 Route 构造函数。结果我想得到类似 Silex Route 匹配的东西:

$app->get('/hello/{name}', function($name) use($app) { 
   return 'Hello '.$app->escape($name); 
});

对不起我的英语......

【问题讨论】:

    标签: php symfony routing silex


    【解决方案1】:

    $matcher->match()返回[1]匹配路由的属性[2](包括一个特殊的_route属性包含路由名称[3]).

    controller 默认值也包含在属性中,因此您可以轻松访问它,然后使用 call_user_func 之类的东西来调用控制器:

    // ...
    $attributes = $match->match($request->getPathInfo());
    
    $controllerResult = call_user_func($attributes['controller']);
    

    【讨论】:

      猜你喜欢
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 2015-12-20
      • 2015-12-09
      • 2011-10-06
      相关资源
      最近更新 更多