1
votes

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?

1
Can you explain what you mean by a dynamic route, please?Problematic
sure, I mean that I have the content of each page in the database with a slug column in the table that serves as "url". When I digit domain.com/test test is the slug and is dynamicStefano
If you are talking about slugs, you should get everything you want on the Symfony2 doc : symfony.com/doc/current/book/routing.htmlNanocom
Ok you need slugs, so read the documentation for version 2Nanocom
so it's more appropriate for a doctrine-based routing to have a controller that does the query?Stefano

1 Answers

6
votes

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.