title: DDD (Domain Driven Design) events and persistance
body: <p>The question here is about how to handle correctly DDD DE, lets say we have this very simple example (i know that for simple projects DDD is not needed, but this is just an example). We have User (Aggregate root) and UserProfile (Value Object), so tables are:</p>
  
  <p>user</p>
  
  <pre><code>- id
  - email
  - password
  </code></pre>
  
  <p>user_profile</p>
  
  <pre><code>- country_id
  - first_name
  - second_name
  </code></pre>
  
  <p>As we know our code should express behavior and should not be data-centric, so for example on one of our hexagonal side (UI browser) we have this application service to handle situation:</p>
  
  <pre><code>//UserService application service
  public static function update($formDTO)
  
  $user-&gt;changeCountry($form-&gt;country);
  $user-&gt;changePassword($form-&gt;password);
  $user-&gt;attributes = $form-&gt;userData();
  $user-&gt;save(); // here we use AR not DDD ORM like; you can see this as entityManager-&gt;flush(); if you like Hibernate or Doctrine.
  </code></pre>
  
  <p>And method <code>changeCountry</code> looks like:</p>
  
  <pre><code> public function changeCountry($country)
   {
       if ($this-&gt;country-&gt;id != $country-&gt;id) {
            $oldCountry = $this-&gt;country;
            $this-&gt;moveToCountry($country);
            ...-&gt;eventsManager-&gt;raise(new UserMovedToCountryEvent(
                [
                    'user' =&gt; $this,
                    'oldCountry' =&gt; $oldCountry,
                    'newCountry' =&gt; $newCountry,
                ],
            ))
       }
   }
  </code></pre>
  
  <p>Questions about <code>changePassword</code> and <code>changeCountry</code> methods:</p>
  
  <ul>
  <li>Should we call <code>save</code> in <code>$user-&gt;changeCountry()</code> ? Should such behavior methods (<code>changePassword</code> and <code>changeCountry</code>) persist object to storage after changing it?</li>
  <li>If it should then should we wrap it in transaction? I think yes, since we have here DomainEvent.</li>
  <li>What if there will be no DomainEvent, should we still persist object to storage? In this case this method (<code>changeCountry</code> or <code>moveToCountry</code>) used to express behavior but should it start transaction ? Is there any recomendations for this one?</li>
  <li>Or maybe we only should rais one domain event <code>UserProfileChanged</code> with params like <code>$oldInfo</code> <code>$newInfo</code>, but as for me this one lacks the domain.</li>
  </ul>
  
  <p>The point is to make things correct, but without unneeded amount of persistance calls. I know that i should not think about persistance on domain layer, but getting <code>20</code> sql updates instead of <code>1</code> is not a good solution.</p>