Using EntityManager inside Doctrine 2.0 entities

前端 未结 4 2150
执笔经年
执笔经年 2020-11-27 03:50

I have 2 entities: Country (id, name) and Mapping (id, object, internalId, externalId). Country and Mapping are not connected with associations (because Mapping has rows not

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 04:36

    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);
    }  
    

提交回复
热议问题