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
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
}
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.
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.