How do I persist models properly in Symfony2?
I have been very puzzled about the concept of model (entity) persistence in Symfony2. AFAIK, there is nothing like model_instance->save() in Symfony2. Instead, it must be invoked in a controller by retrieving the doctrine entity manager, and then persist the model_instance and flush the model_instance.
- If I have a Blog model, which contains variable Tag model instances and Category model instances, which will be generated from the blog message body. However, I do not know how I can create a Blog factory to also save these tags and categories, instead I must return these "Tag" and "Category" instances from a factory (which it won't persist anyway) --- there is no way I can persist the blog and persist the tags and categories all within a single method in the Blog.
In fact, if I want to write a script that is invoked periodically to persist models, it seems impossible, because it must invoke the controller, and yet I don't see why a script requires a web server to be present, but not just work on the object model without touching the web server.
I really appreciate how to resolve the problems above. Thank you!
By default, when you create an entity with some relations, you have to persist your main entities and its relations manually. But you can change this behavior activating the persistence cascade:
In your comments you mentioned testing. There is a cookbook library about testing doctrine right here: http://symfony.com/doc/current/cookbook/testing/doctrine.html
Symfony2 is actually a decoupled bundle of libraries. while the default way to use doctrine is through the controller, you can load the doctrine libraries directly. I'm not sure how you access the doctrine bundle on its own, but I'm sure the examples in the article above will help with that.
Also, Fabien Potencier (the lead developer of symfony) gave a talk recently about Symfony being a bunch of bundles which can be used independently. He covered the basics of how to use a large portion of the bundles. You can view that here: http://symfony.com/video/Paris2011/583