symfony 2按模型路由


symfony 2 routing by model

Sf2.0,例如标准博客。

路由代码yml:

DevBlogBundle_post_show:
 pattern:  /posts/{id}
 defaults: { _controller: "DevBlogBundle:Post:show" }
 requirements:
    _method:  GET
    id: 'd+

我为我的帖子生成url的标准方式使用:

path('DevBlogBundle_post_show',{'id':post.id})

我在所有的条目/布局中都使用了这种解释,其中包括帖子列表。如果我想更改postronghow的路由(比如…添加Slug参数/posts/{id}.{Slug}),我需要更改所有的temlates。相反,我想通过我的Post模型生成路线,类似于:

public function getUrl(){
     return $this->generator->generate('DevBlogBundle_post_show',array (...params...));}

问题:我如何将此生成器添加到我的Post模型中,我必须"使用…"什么,以及如何生成路线?

在我的模板中,我想放置:

<a href="{{ post.getUrl() }}" ...>...</a>

提前谢谢。

这个问题和我之前评论中的想法让我很兴奋,我已经拼凑了一个快速的概念验证,以实现您的要求。我已经实现了一个可以传递实体和路由名称的trick函数。该函数执行以下设置以生成url:

  1. 获取按名称指定的路线
  2. 编制路线
  3. 获取路线变量
  4. 循环变量并尝试调用实体上的相应getter,以构建UrlGeneratorInterface生成路由url所需的参数数组
  5. 让symfony的url生成器生成url

然而,这意味着路由参数的命名与实体中的属性完全相同,无论如何,IMHO都是一种很好的做法。需要将代码放入一个分支扩展中,该扩展将服务容器引用注入到容器属性中。

public function generateEntityUrl($entity,$routeName)
{
    $router         = $this->container->get('router');
    $generator      = $router->getGenerator();
    $collection     = $router->getRouteCollection();
    $route          = $collection->get($routeName);
    $compiledRoute  = $route->compile();
    $variables      = $compiledRoute->getVariables();
    $parameters     = array();
    foreach($variables as $var)
    {
        $getter = 'get'.ucfirst($var);
        $parameters[$var]=$entity->$getter();
    }
    return $generator->generate($routeName,$parameters);
}

在trick中,您可以使用{{post|entity_url('DevBlogBundle_post_show')}}调用该函数。

但我在问自己,为什么symfony中还没有实现。。。或者为什么我还没有找到它。

好的。。。并且到目前为止仍然没有将实体参数传递到路由器的功能。按房间13回答是有道理的,但我认为这样更容易:

在Twig Templates或Haml(强烈建议,节省时间,它会让你更快乐:https://github.com/arnaud-lb/MtHamlBundle)等:

{{ path('route_name', entity.toParam()) }}

在实体中定义如下函数:

public function toParam(){
  // maybe some logic....
  return array(
    'id' => $this->id,
    'slug' => $this->getSlug(),
    .....other needed params
  );
}

原因:如果您的路由参数是新出现的选项,只需将其添加到实体#toParam中的一个位置,而不是查找使用路由的位置,并覆盖所有分支模板。