Monday, September 26, 2011

Deal with SET field in your entities with Doctrine2 / Symfony2

Given MyEntity is an entity (mapping table my_entity), given mySetField is a MySQL SET field from this entity (mapping column my_set_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
{
   //SET de la colonne my_set_field
   const MY_SET_FIELD_VALUE1 = 'Value1';
   const MY_SET_FIELD_VALUE2 = 'Value2';
   const MY_SET_FIELD_VALUE3 = 'Value3';

   static private $_mySetFieldValues = null;

   /**
    * @var array $mySetField
    */
   private $mySetField;

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

   /**
    * Set mySetField
    *
    * @param array $mySetField
    */
   public function setMySetField(array $mySetField)
   {
      foreach ($mySetField as $mySetValue)
      {
         if (!in_array($mySetValue, self::getMySetFieldChoices()))
         {
            throw new \InvalidArgumentException(
               sprintf('Invalid value for my_entity.my_set_field : %s.', $mySetValue)
            );
         }
      }

      $this->mySetField = implode(',', $mySetField);
   }

   /**
    * Get mySetField
    *
    * @return array
    */
   public function getMySetField()
   {
      return explode(',', $this->mySetField);
   }

}
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 ReflectionClass enhancement ;)

No comments :

Post a Comment

Comments are moderated before being published.