Note that there are some explanatory texts on larger screens.

plurals
  1. PODoctrine2 Best Practice, Should Entities use Services?
    text
    copied!<p>I asked a similar question a while back: <a href="https://stackoverflow.com/questions/3738687/using-the-data-mapper-pattern-should-the-entities-domain-objects-know-about-th">Using the Data Mapper Pattern, Should the Entities (Domain Objects) know about the Mapper?</a> However, it was generic and <strong>I'm really interested in how to accomplish a few things with Doctrine2 specifically</strong>.</p> <p>Here's a simple example model: Each <code>Thing</code> can have a <code>Vote</code> from a <code>User</code>, a <code>User</code> may cast more than one <code>Vote</code> but only the last <code>Vote</code> counts. Because other data (<code>Msssage</code>, etc) is related to the <code>Vote</code>, when the second <code>Vote</code> is placed the original <code>Vote</code> can't just be updated, it needs to be replaced.</p> <p>Currently <code>Thing</code> has this function:</p> <pre><code>public function addVote($vote) { $vote-&gt;entity = $this; } </code></pre> <p>And <code>Vote</code> takes care of setting up the relationship:</p> <pre><code>public function setThing(Model_Thing $thing) { $this-&gt;thing = $thing; $thing-&gt;votes[] = $this; } </code></pre> <p>It seems to me that ensuring a <code>User</code> only has the last <code>Vote</code> counted is something the <code>Thing</code> should ensure, and <a href="http://martinfowler.com/bliki/AnemicDomainModel.html" rel="nofollow noreferrer">not some service layer</a>.</p> <p>So to keep that in the Model, the new <code>Thing</code> function:</p> <pre><code>public function addVote($vote) { foreach($this-&gt;votes as $v){ if($v-&gt;user === $vote-&gt;user){ //remove vote } } $vote-&gt;entity = $this; } </code></pre> <p><strong>So how do I remove the <code>Vote</code> from within the Domain Model?</strong> Should I relax <code>Vote::setThing()</code> to accept a <code>NULL</code>? Should I involve some kind of service layer that <code>Thing</code> can use to remove the vote? Once the votes start accumulating, that <code>foreach</code> is going to be slow - should a service layer be used to allow <code>Thing</code> to search for a <code>Vote</code> without having to load the entire collection?</p> <p>I'm definitely leaning toward using a light service layer; however, <strong>is there a better way to handle this type of thing with Doctrine2, or am I heading in the right direction?</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload