3

I am trying to get a multi-tenant system setup where each user has their own prefixed tables.

So my database might look like

users
acme_posts
my_posts
their_posts
our_posts

A solution like this is a good start, but it does not allow for the prefix to be dynamically created.

Is it possible to modify the doctrine solution above to set the database prefix based on the logged in user?

Another approach might be to have a main users database and then have separate databases for the user specific tables, but I am not sure if Doctrine can handle relationships between multiple databases.

All suggestions are welcome.

1 Answer 1

0

You can quite easily get access to the service container in a Doctrine EventListener like that, simply by defining the EventListener as a service (instructions located here). However, that approach won't help you for your situation, as all the class metadata will be loaded just once and cached, so it can't know about different users.

I don't know your use-case, obviously, but is there any reason that you can't simply add a field to your *_posts table, such that you have one posts table with "user_namespace" or similar as part of the key?

If your objection is simply to cluttering your controller logic with information about what user is logged in, you can simplify things by using a prePersist Doctrine EventListener to set the appropriate user_namespace on new entities, and either a Filter (for Doctrine >=2.2) or a custom DQL walker (for everything else) to restrict all your queries to only retrieve entities from the appropriate user_namespace.

2
  • I am not sure I understand the "user_namespace" correctly. Do you mean to have one posts table that has a relating field to the id field in the users table? I am trying to avoid this to keep tenant data separate and keep table sizes to a minimum, but maybe this is the way to go...
    – Mike
    Jul 14, 2012 at 16:56
  • Yep, that's precisely what I mean - the only other elegant solution that I can think of is to use different instances of the app per-user, configured to use different databases. This is easy enough to do but means that you have to duplicate all common data (for instance your users table), as Doctrine doesn't support cross-database associations as far as I know Jul 14, 2012 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.