Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>While it's not the most elegant, you can get a little pragmatic, and just use string keys in a fairly efficient, safe, way:</p> <pre><code>&lt;?php class Booking { protected $statusMap = array( 0 =&gt; 'new', 1 =&gt; 'accepted', 2 =&gt; 'rejected' ); /** * A premature optimization, trading memory to reduce calls to * array_flip/array_search in a more naive implementation * * @var array */ protected $statusMapReverse; public function __construct(){ $this-&gt;statusMapReverse = array_flip($this-&gt;statusMap); $this-&gt;setStatus('new'); } /** * @ORM\Column(type="integer") */ protected $status; /** * @param string $status Valid values are 'new', 'accepted', and 'rejected' * * @throws InvalidBookingStatusException */ public function setStatus($status){ if (! in_array($status, $this-&gt;statusMap)){ throw new InvalidBookingStatusException(); } $this-&gt;status = $this-&gt;statusMapReverse[$status]; } /** * @return string */ public function getStatus(){ return $this-&gt;statusMap[$this-&gt;status]; } /** * @return integer */ public function getStatusCode(){ return $this-&gt;status; } /** * @return array */ public function getStatusMap(){ return $this-&gt;statusMap; } } </code></pre> <p>I find I use this pattern pretty frequently when I need to model this kind of enumeration-like data. It has a few nice features:</p> <p>1) Status is stored as in integer in the db.</p> <p>2) Calling code doesn't ever need to care about those (integer) values, unless it wants to.</p> <p>3) Calling code is protected against typos/invalid status since setStatus validates strings (can only be checked at runtime, but hey)</p> <p>4) Booking::getStatusMap() makes it easy to generate select boxes, etc.</p> <p>You could expand setStatus to accept either a string or integer (status-code), and still validate, if you wanted to be able to set status by code.</p> <p>The disadvantages (compared to using constants), are mainly:</p> <p>1) Querying by status becomes a bit of a hassle. Client code needs to getStatusMap() and find codes.</p> <p>2) IDEs won't be quite as helpful in telling calling code what valid statuses are (though the phpdoc annotation on setStatus() can help, if you keep it up-to-date.</p> <p>3) Invalid status throws an exception at runtime, while with constants you find out at compile-time. </p> <p>--</p> <p>Final note, I don't see the need for a BookingManager at all. Yes, entities are just plain objects, but that doesn't mean they can't contain logic to manage their own state.</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