Symfony2检查Db上的路由

one question about Symfony2 and the routes.

In my routing file i have this route:

offers_category:
    pattern: /offers/{category}
    defaults: { _controller: MyBundle:Offers:category}

In this way i can call any url and all of them will respond with an 200 (HTTP CODE). The categories list is dynamic, inserted by an admin panel (created with Sonata) and saved on db.

I would like to check if the "category" exist and then respond with 200 or 404. There is a way to tell to Symfony2 (in the route file) the dictionary available for the placeholder?

I think that i have to check inside my controller calling a query on db, but i hope to find a better or cleaned solution.

Thanks all


I found the solution!

Thanks to @lenybernard for the precious advice on his post.

With the @lenybernard solution i was able to configure a route with an indexed field like:

www.sitename.com/offers/1

but i needed a url like:

www.sitename.com/offers/travel

and to do that i used this method to mapping a label not indexed to an url:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use NameProject\MyBundle\Entity\Category;

/**
* @Route("/offers/{category}")
* @ParamConverter("type", class="NameProjectMyBundle:Category", options={"mapping": {"category": "name"}})
*/

...and everthing works!

There is a simple and nice way called ParamConverter to do but there is nothing to do in the routing file directly (furthermore this is not its role) and you're right, this is ControllerSide :

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use My\Bundle\MyBundle\Entity\Offers\Category;

class OffersController
{
    /**
     * @param Category $category
     * @ParamConverter("category", class="MyBundle:Offers/category")
     */
    public function showAction(Category $category)
    {
        ...
    }
}

As said in the documentation, several things happen under the hood:

The converter tries to get a MyBundle:Offers/category object from the request attributes (request attributes comes from route placeholders -- here id); If no Category object is found, a 404 Response is generated; If a Category object is found, a new category request attribute is defined (accessible via $request->attributes->get('category')); As for other request attributes, it is automatically injected in the controller when present in the method signature. If you use type hinting as in the example above, you can even omit the @ParamConverter annotation altogether because it's automatic :

So you just have to cast the variable and the param converter will throw a 404 automatically, cool right ?

use My\Bundle\MyBundle\Entity\Offers\Category;

class OffersController
{
    /**
     * @param Category $category
     */
    public function showAction(Category $category)
    {
        ...
    }
}