I'd like to modify a table's schema/DB name at runtime as is possible with the table name, but the ClassMetadataInfo
class does not appear to expose an interface to get/set this property.
I can make do with modifying table names at runtime if absolutely necessary, but it is not an ideal solution due to the amount of tables we would then have to store in a single schema/DB.
Is there a way to achieve what I'd like to do? Thanks in advance.
Note: I need to be able to provide a fully qualified table name using a schema placeholder in my annotation-based entity mapping (like __schema_placeholder__.table_name
, for cross-database joins). At runtime I would then like to dynamically remap the entity from __schema_placeholder__.table_name
=> real_schema_name.table_name
.
You can dynamically adjust the table names ( and mappings ) by hooking into the doctrine event-system with listeners/subscribers.
i.e. "loadClassMetadata" is one of doctrine's events you can create a listener/subscriber for as described in the cookbook article How to Register Event Listeners and Subscribers.
Example
config.yml
MappingListener
ClassMetadata extends ClassMetadataInfo and provides a public variable "table" ( containing the mapping information provided by your annotations or yml ) which you can modify !
The public table variable is an array with the following entries:
You can dynamically register event-listeners/subscribers in your controller prior to saving/updating.
Furthermore you can introduce multiple database connections/names and access them in your application.
app/config/config.yml
Then get different entity managers using ...
or repositories
... or add connections dynamically
Read more about the topic in the cookbook chapter How to work with Multiple Entity Managers and Connections.
You can make use of the undocumented 'options' parameter in @Table and pass a variable to the listener which you can use to decide which database to use.
'options' is used to include DBMS specific options in the SQL when generating the schema. For example: "charset"="utf8mb4", "engine"="InnoDB", etc
When choosing a variable name, make sure it is not a valid option supported by your DBMS. In the below example I have chosen 'schema':
After that I have created a parameter array in services.yml called 'schema', which will be passed to the service via the ParameterBag. The values are either edited in the yml, or pulled from the environmental variables.
Now my listener looks like this:
This results in all entities with the table option 'schema' will be set to use the database that is defined in the parameters in the service.yml or in environmental variables.
This means you can choose to set the schema, or leave it as default, without editing the entities or any other class.