Extending Doctrine EntityManager with EntityManagerDecorator leaves wrong reference in UnitOfWork
I would suggest to decorate (and not directly extend) the EntityManager
, as it looses the coupling between your implementation and the inherited component.
In order to be able to distinguish entities that do have a relationship to a tenant implement/extend those classes from an interface
or a mapped superclass
.
The securityContext (for demonstration purpose) is there to get the reference to the tenant.
/** * `EntityManagerDecorator` exists since v2.4 */class MultiTenantEntityManager extends EntityManagerDecorator { private $securityContext; public function __construct(EntityManagerInterface $entityManager, $securityContext) { parent::__construct($entityManager); $this->securityContext = $securityContext; } public function persist($entity) { // set the tenant before persisting an entity if ($entity instanceof MultiTenantEntity) { $userId = $this->securityContext->getUserId(); $tenant = $this->wrapped->find($userId,...); $entity->setTenant($tenant); } return $this->wrapped->persist($entity); }}