Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would suggest subtracting the sold items right away from <code>Product::available_items</code>. This would resolve the issue right away, because <code>Product::available_items</code> would always reflect the number of available items.</p> <p><strong>Method no. 1</strong></p> <p>Subtract <code>Sale::quantity</code> from <code>Product</code> right away.</p> <pre class="lang-php prettyprint-override"><code>public function setProduct(ProductInterface $product) { $new_count = $product-&gt;getAvailableItems() - $this-&gt;getQuantity(); $product-&gt;setAvailableItems($new_count); $this-&gt;product = $product; } </code></pre> <p>You'd also have to do the subtracting in all the controllers that might change the available item count.</p> <hr> <p><strong>Method no. 2</strong></p> <p>Personally, I would actually favor this method over the first one, because it keeps the logic in a single place and generally results in shorter controllers. In addition, my entities are usually long enough without all the domain logic.</p> <p>Assuming <code>Sale</code> has a reference to a <code>Product</code>, I'd put the logic into a service (an entity-specific entitymanager, e.g <a href="https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Model/UserManagerInterface.php" rel="nofollow"><code>UserManager</code></a>. It'd be called <code>SaleManager</code> in our case). The method in it would look something similar to:</p> <pre class="lang-php prettyprint-override"><code>public function updateSale(SaleInterface $sale, $flush = true) { $product = $sale-&gt;getProduct(); $new_count = $product-&gt;getAvailableItems() - $sale-&gt;getQuantity(); if ($new_count &lt; 0) { throw new NegativeQuantityException(); } $product-&gt;setAvailableItems($new_count); $this-&gt;em-&gt;persist($sale); if (true === $flush) { $this-&gt;em-&gt;flush(); } } </code></pre> <p>I didn't touch the issue of what would happen if you were to remove a <code>Sale</code> from a <code>Product</code> or switch a <code>Product in a sale</code>, but you must certainly consider this as well.</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