Sunday, September 18, 2011

Deal with ENUM fields in your entities with Doctrine2 / Symfony2

MyEntity is an entity (mapping table my_entity), myEnumField is a MySQL ENUM field from this entity (mapping column my_enum_field). Its admissible values are 'Value1', 'Value2' and 'Value3' :
<?php

namespace MyCompany\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * MyCompany\MyBundle\Entity\MyEntity 
 */
class MyEntity
{
   //ENUM de la colonne my_enum_field 
   const MY_ENUM_FIELD_VALUE1 = 'Value1';
   const MY_ENUM_FIELD_VALUE2 = 'Value2';
   const MY_ENUM_FIELD_VALUE3 = 'Value3';

   static private $_myEnumFieldValues = null;

   /**
    * @var string $myEnumField 
    */
   private $myEnumField;

   static public function getMyEnumFieldChoices()
   {
      // Build $_myEnumFieldValues if this is the first call
      if (self::$_myEnumFieldValues == null)
      {
         self::$_myEnumFieldValues = array ();
         $oClass = new \ReflectionClass('\MyCompany\MyBundle\Entity\MyEntity');
         $classConstants = $oClass->getConstants();
         $constantPrefix = "MY_ENUM_FIELD_";
         foreach ($classConstants as $key => $val)
         {
            if (substr($key, 0, strlen($constantPrefix)) === $constantPrefix)
            {
               self::$_myEnumFieldValues[$val] = $val;
            }
         }
      }
      return self::$_myEnumFieldValues;
   }

   /**
    * Set myEnumField 
    * 
    * @param string $myEnumField 
    */
   public function setMyEnumField($myEnumField)
   {
      if (!in_array($myEnumField, self::getMyEnumFieldChoices()))
      {
         throw new \InvalidArgumentException(
            sprintf('Invalid value for my_entity.my_enum_field : %s.', $myEnumField)
         );
      }

      $this->myEnumField = $myEnumField;
   }

}
We will no longer refer to values ​​of the field but to the constants, it allows to centralize these values ​​somewhere ! PS: Thanks to guyaloni (http://forum.symfony-project.org/viewtopic.php?f=23&t=37406&p=125387#p125382) for the ReflectrionClass enhancement ;)

No comments :

Post a Comment

Comments are moderated before being published.