Symfony2 & MongoDB ODM: Adding the missing ParamConverter
Matthias Noback
Just a quick post…
What seems to be missing from the DoctrineMongoDBBundle is a ParamConverter service which resolves request attributes to controller arguments by fetching a Document using the MongoDB DocumentManager. For entities, this would work:
/**
* @Route("/blog/{id}
*/
public function showAction(Post $post)
{
// $post will be the entity Post with the "id" taken from the route pattern
}
This works because of the DoctrineParamConverter, which is registered by default by the SensioFrameworkExtraBundle. But only for Doctrine ORM, and not for Doctrine MongoDB ODM. As Christophe Coevoet mentioned when someone tried to implement this missing feature, it can be added easily by yourself, without writing any PHP code, though it might not be so clear how to accomplish this. Still, the only thing you have to do is add a service to your services.xml
file:
<service id="doctrine_mongo_db_param_converter" class="Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter">
<argument type="service" id="doctrine_mongodb" />
<tag name="request.param_converter" converter="doctrine.odm" />
</service>
As you can see, the DoctrineParamConverter
is reusable, but it receives the ManagerRegistry for MongoDB ODM instead of the ORM.
So now, when Post
is a Document, it will be fetched by its ID, just like if it were an Entity.
Please check out the ParamConverter documentation when you don’t use the default Document manager, or when the value of the Document’s identifier is not in the request attribute “id”.