Doctrine2 Best Practice, Should Entities use Services?

ぃ、小莉子 提交于 2019-11-30 10:22:08
Bryan M.

I vote for the service layer. I've often struggled with trying to add as much logic on the Entity itself, and simply frustrated myself. Without access to the EntityManager, you're simply not able to perform query logic, and you'll find yourself using a lot of O(n) operations or lazy-loading entire relationship sets when you only need a few records (which is super lame when compared to all the advantages DQL offers).

If you need some assistance getting over the idea that the Anemic Domain Model is always an anti-pattern, see this presentation by Matthew Weier O'Phinney or this question.

And while I could be misinterpreting the terminology, I'm not completely convinced that Entities have to be the only objects allowed in your Domain Model. I would easily consider that the sum of Entity objects and their Services constitutes the Model. I think the anti-pattern arises when you end up writing a service layer that pays little to no attention to separation of concerns.

I've often flirted with the idea of having all my entity objects proxy some methods to the service layer:

public function addVote($vote)
{
   $this->_service->addVoteToThing($vote, $thing);
}

However, since Doctrine does not have any kind callback event system on object hydration, I haven't found an elegant way to inject the service object.

My advice would be to put all the query logic into an EntityRepository and then make an interface out of it sort of like:

class BlogPostRepository extends EntityRepository implements IBlogPostRepository {}

that way you can use the interface in your unit-tests for the service objects and no dependency on the EntityManager is required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!