Using EntityManager inside Doctrine 2.0 entities

It is not a good idea to allow an entity object to rely on the entity manager. It ties the entity to the persistence layer, which was a problem Doctrine 2 was specifically trying to solve. The biggest hassle in relying on the entity manager is that it makes your model hard to test in isolation, away from the database.

You should probably be relying on service objects to handle the operations that rely on the entity manager.

// CountryService
public function getExternalId($country) {}

Additionally, you could create proxy methods on your model to call out to a service object that is set externally. A service object would be much easier to mock while testing than the entity manager would be.

$country->setService($countryService);
$country->getExternalId();

// Country
public function getExternalId()
{
   $this->_service->getExternalId($this);
}  

Leave a Comment