基于学说的自定义symfony路由 [英] Custom symfony routing based on doctrine
问题描述
我需要使用symfony 2的动态路由,其中一个slug参数添加到url中,并且与数据库中的页面相关。每个页面都有一个自己的slug,其内容存储在数据库中。我阅读了文章高级路由,但它是旧版的symfony。对于新版本,似乎 ParamConverter 也做了类似的工作。这是实现基于教义的路由的正确方法还是应该写一个真正的自定义路由器类?
I need to have dynamic routes with symfony 2 where a slug parameter is added to the url and is related to a page in the database. Each page has a own slug and its content stored in the database. I read the article Advanced Routing but it's for the old version of symfony. For the new version it seems that ParamConverter does a similar job. Is this the correct way to implement a doctrine-based routing or should I write a real custom router class?
推荐答案
一个ParamConverter,是的。 FrameworkExtraBundle附带的默认 DoctrineParamConverter 可以处理大多数简单的例子 - 也就是说,它知道如何使用与路由占位符名称相同的字段来查找类型化对象:
I would use a ParamConverter, yes. The default DoctrineParamConverter that ships with the FrameworkExtraBundle can handle most simple cases -- that is, it knows how to look up a typehinted object by a field with the same name as the route placeholder:
// routing.yml
foo_route:
pattern: /{slug}/
defaults: { _controller: FooVendorBundle:Foo:view }
// FooVendorBundle/Controller/FooController.php
public function view(FooEntity $foo)
{
// $foo will be an instance of FooEntity
}
通常,在控制器的参数列表中,您将有一个 $ slug
变量将从路由捕获的 {slug}
的内容填充。但是,使用ParamConverter,它会认识到您要求一个 FooEntity
类,并将尝试通过捕获的 slug
value并填充该实体的 $ foo
变量。
Normally, in a controller's argument list, you'd have a $slug
variable that would be populated from the contents of {slug}
captured by the route. However, with the ParamConverter, it recognizes that you're requesting a FooEntity
class, and will try to find that entity by the captured slug
value and populate the $foo
variable with that entity.
默认的ParamConverter是,仅限于仅在实体上查找实际存在的属性:如果FooEntity没有名为 slug
的字段,则查找将失败并将抛出异常。就像我说的,这将处理大多数基本用例。如果您需要更多的深入转换请求参数,您可以随时自己编写。
The default ParamConverter is, of course, limited to only being able to look up properties that actually exist on the entity: if FooEntity does not have a field named slug
, the lookup will fail and an exception will be thrown. Like I said, this will handle a majority of basic use cases. If you need more in-depth conversion of request parameters, you could always write your own.
这篇关于基于学说的自定义symfony路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!