sql-table-prefixes.rst 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. SQL-Table Prefixes
  2. ==================
  3. This recipe is intended as an example of implementing a
  4. loadClassMetadata listener to provide a Table Prefix option for
  5. your application. The method used below is not a hack, but fully
  6. integrates into the Doctrine system, all SQL generated will include
  7. the appropriate table prefix.
  8. In most circumstances it is desirable to separate different
  9. applications into individual databases, but in certain cases, it
  10. may be beneficial to have a table prefix for your Entities to
  11. separate them from other vendor products in the same database.
  12. Implementing the listener
  13. -------------------------
  14. The listener in this example has been set up with the
  15. DoctrineExtensions namespace. You create this file in your
  16. library/DoctrineExtensions directory, but will need to set up
  17. appropriate autoloaders.
  18. .. code-block:: php
  19. <?php
  20. namespace DoctrineExtensions;
  21. use \Doctrine\ORM\Event\LoadClassMetadataEventArgs;
  22. class TablePrefix
  23. {
  24. protected $prefix = '';
  25. public function __construct($prefix)
  26. {
  27. $this->prefix = (string) $prefix;
  28. }
  29. public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
  30. {
  31. $classMetadata = $eventArgs->getClassMetadata();
  32. $classMetadata->setTableName($this->prefix . $classMetadata->getTableName());
  33. foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
  34. if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY) {
  35. $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name'];
  36. $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName;
  37. }
  38. }
  39. }
  40. }
  41. Telling the EntityManager about our listener
  42. --------------------------------------------
  43. A listener of this type must be set up before the EntityManager has
  44. been initialised, otherwise an Entity might be created or cached
  45. before the prefix has been set.
  46. .. note::
  47. If you set this listener up, be aware that you will need
  48. to clear your caches and drop then recreate your database schema.
  49. .. code-block:: php
  50. <?php
  51. // $connectionOptions and $config set earlier
  52. $evm = new \Doctrine\Common\EventManager;
  53. // Table Prefix
  54. $tablePrefix = new \DoctrineExtensions\TablePrefix('prefix_');
  55. $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix);
  56. $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config, $evm);