Search code examples
symfonyormdoctrineentitymanager

Working with 2 databases and just one entity manager in Symfony2


I need to keep an archive database to an application in Symfony2. In it I'll keep all records older than 90 days. I was thinking that I could use just one entity manager (because both databases are identical).

First of all, I'm not sure if this is the best approach/solution. And, besides that, I don't know how to implement this idea (I've just found 2 entity managers for 2 databases).

I'm sorry if this is a dumb question, but I've been looking for some solution for it for 2 days now.


Solution

  • This isn't possible, each Entity Manager can only use one DB connection, the docs seem quite clear about it.

    So I think you'll be stuck with using two EMs. Each will be configured with a duplicate set of your mappings. The detail of how you use them is up to you though:

    • You could just manually choose one or the other as required in your app
    • You could somehow abstract it away into a class of your own which has both EMs, and then when you run queries etc it will be worrying about where to get the data from (and possibly how to combine data from both EMs)
    • If the only activity which really needs both EMs is the archive process itself, that's an obvious thing to hide away in a class nicely

    I suppose it also depends on what the point of the archive DB is. If it's some architectural thing like it needs to be on a different server or whatever, then you're stuck as above. On the other hand, if you really just want old data not to show up in day-to-day queries (without specifically asking for it), then it might be better to implement some kind of "archived" flag and a Doctrine Extension which magically hides archived items away until you ask for them, very similar to SoftDeleteable