Dynamically switching databases with same schema using Phalcon ORM

Hey, I need to dynamically create new database for each customer. All the databases have the same schema. How Can i switch between that databases (If i know everything about them) using Phalcon ORM? All the databases will be stored on the same database server (postgres).

Well i would recommend to just overwrite current db service with new database name. You can also try use setModelSchema from modelsManager but that would mean that you need database user with access to all databases obviously and im not sure it's good idea.

edited May '16

Do you need to be able to switch between multiple databases during a single execution cycle or just to be able to dynamically create them? If you only need to dynamically create the database then you could do that with direct PDO access and to point it towards the new schema.

You could do something like the following in your customer DB service definition:

    // make getSelected() fail if a customer wasn't selected
    $record = $record->getSelected();
    $dbname = 'prefix_' . $record->uuid;

Or if you need to dynamically switch the database you could add a function in the Customers model that defined the service from a method call or access another function somewhere which then sent in some arguments. You could also add a global function into your services.php file that could set it up by receiving a Customers record. I think that whatever hackery that you use that you should try to keep the service definition details in the services file.

If you are only going to be dealing with one customers data during an execution style then you can remove a lot of edge cases.

Another thing to consider is that if you need to query customer data then you can create another admin/system table that stores this stuff whether it is duplicate or original data. Then use model hooks somewhere to keep the information up to date.