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 interf
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':
@ORM\Table(name="person", options={"schema"="readonly"})
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.
parameters:
env(SCHEMA_READONLY): 'readonly_database' #default if env variable has not been set
schema:
readonly: 'readonly_database'
client: 'client_database'
runtime: '%env(SCHEMA_READONLY)%' #pulled from env variables
Now my listener looks like this:
class MappingListener
{
protected $parameterBag;
public function __construct(ParameterBagInterface $parameterBag) {
$this->parameterBag = $parameterBag;
}
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) {
$schemaParamaters = $this->parameterBag->has('schema') ? $this->parameterBag->get('schema') : array();
$classMetadata = $eventArgs->getClassMetadata();
if(isset($classMetadata->table['options']['schema']) && isset($schemaParamaters[$classMetadata->table['options']['schema']])) {
$classMetadata->setPrimaryTable(['schema' => $schemaParamaters[$classMetadata->table['options']['schema']]]);
}
}
}
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.