[EXTENSION] enum

I’ve published a piece of code to try to emulate enums in PHP.

You can take a look at it here:

http://www.yiiframework.com/extension/enum/

It contains methods to make use of yii components (dropdowns, radio button lists, model rules, etc.) easier.

Some examples:

Declaring




class MyEnum extends Enum

{

  const MY_ENUM_VALUE1 = "MY_VALUE_1";

  const MY_ENUM_VALUE2 = "MY_VALUE_2";

}



Translating (i18n support in Yii)




return array(

    MyEnum::MY_ENUM_VALUE1 => 'My value 1',

    MyEnum::MY_ENUM_VALUE2 => 'My value 2',);



Rules validation




public function rules()

{

  return array( 

    (...),

    array( 'enum_field', 'in', 'range' => MyEnum::getValidValues() ),

    (...),

  );

}



Radio button:




$form->radioButtonList( $model, 'enum_field', MyEnum::getDataForRadioButtonList() );



Drop down list:




$form->dropDownList( $model, 'enum_field', MyEnum::getDataForDropDown() );



Use an enum value:




echo MyEnum::MY_ENUM_VALUE_1;



Declare a DBEnum




class MyEnum extends DBEnum

{

  const MY_ENUM_VALUE1 = "MY_VALUE_1";

  const MY_ENUM_VALUE2 = "MY_VALUE_2";

 

  protected function getDBField()

  {

      return 'my_enum_id_field';

  }

 

  protected function getDBTable()

  {

      return 'myenum_table';

  }

 

  // Optionally define a condition if only some values of 

  //the table are to be taken into consideration

  /*

  protected function getDBCondition()

  {

      return "other_field=value";

  }*/

 

}

A DBEnum is like an Enum but it performs a first-time check of the declared values agains a DB table. If not interested in this feature, just use the regular Enum class.

Updated with a better support for DB Enums. Also fixed a little bug with dropdowns…

Hi,

When I try to use DBEnum I get this error:

Missing argument 1 for CDbConnection::createCommand(), called in /var/www/w1/protected/extensions/DBEnum/DBEnum.php on line 67

In my Controller I have:

class EventTypeEnum extends DBEnum

{

const MY_ENUM_VALUE1 = "Rye";

const MY_ENUM_VALUE2 = "Pumernickel";

protected function getDBField()

{

  return 'EventType';

}

protected function getDBTable()

{

  return 'Event';

}

}

In my View I Have:

<?php

 echo CHtml::activeDropDownList(  &#036;eModel, 'EventType',


 EventTypeEnum::getEnum()-&gt;getDataForDropDown());


        ?&gt;

Do you have any idea what Im doing wrong?

Thanks

Hi, sorry for the delay.

Have you tried debugging to see what’s happening?

Could you try this, please?




<?php

$myEnums = EventTypeEnum::getEnum()->getDataForDropDown();

/* ***** dump $myEnums to check its value **** */

echo CHtml::activeDropDownList( $eModel, 'EventType',

EventTypeEnum::getEnum()->getDataForDropDown());

?>



Have you added "Rye" and "Pumernickel" to your "Event" table ?

BTW, just an advice: your constants should look like:




class EventTypeEnum extends DBEnum

{

const RYE = "Rye";

const PUMERNICKEL = "Pumernickel";

(...)

}



so when you use them in your code it’s easier to identify them ;)

Updated with a cleaner interface. Take a look at the extension page

Hi. Thanks for the extension, it works great so far.

I have a question concerning what is stored in the db and what is shown to the user. I want to have Enum of different statuses like


class BookingStatusEnum extends Enum

{

	const requested 	= '10_requested';

	const reserved 		= '20_reserved';

	const booked		= '30_booked';

}

These values are stored in my DB after saving the model/form. But what I want to show to the user is a localized description of these statuses.

Therefore I have a en/enums.php




return array(

	BookingStatusEnum::requested => 'requested',

)



and a de/enums.php:




return array(

	BookingStatusEnum::requested => 'angereist',

)



And the problem is that this localization only works for the language which is not defined as source language. How can I change that?

Thanks in advance,

Stefan

For using with migrations I added function that returns SQL (MySQL) code for enum column to Enum class.

Looks like this




    protected function _getColumnSQL()

    {

        return "enum('".

            implode("', '", $this->getDataForDropDown()).

            "') NOT NULL";

    }

Using in migration like this


 $this->createTable(

            'tbl_table',

            array(

                'id' => 'pk',

                'enum_column' => MyEnum::getColumnSQL()

            )

        );

It may be helpful to someone. I don’t know does the autor support extension right now, but either way there is now git repo were I can send a pull request. Also tried to add a comment here http://www.yiiframework.com/extension/enum/ but I’m to new to add a comment there.

Also there are cases when you want not to use costant notation (MyEnum::MYCONSTANT). It happenes when you have to store constant names in variables or smth like that.

For example I’m using Twig template engine with twig-renderer extension. In my case I have messages that can be “new” or “readed”. So in views I want to check if the message attribute status equals STATUS_NEW constant in my MessageStatusEnum. I tried to do it in several ways and I think that my solution is one of the easiest.

I added to my twig globals my MessageStatusEnum, so now it is possible to call it’s functions or get it’s properties, but twigs “constant” function raise PHP warning “constant(): Couldn’t find constant ETwigViewRendererStaticClassProxy::STATUS_NEW”. So at the end I’ve added to Enum class those functions and field


    public $_keyedValues;

    private function getInternalKeyedValuesByReflection()

    {

        if( empty( $this->_keyedValues ) )

        {

            $reflection = new ReflectionClass( get_class( $this ) );

            $consts = $reflection->getConstants();

            $this->_keyedValues = array( );

            foreach( $consts as $constName => $constValue )

            {

                $this->_keyedValues[$constName] = $constValue;

            }

        }

        return $this->_keyedValues;

    }




    protected function _getValue($name)

    {

        $values = $this->getInternalKeyedValuesByReflection();

        return $values[$name];

    }



Now I can get values like this


MyEnum::getValue('CONSTANT_NAME')

That also might be helpful to someone.

Hi, I would like to say that I liked this extension.

But I am unfortunately facing an annoying problem to use this.

As I saw in the page, I downloaded the zip extension (enums 2.zip) but now I don’t know how to apply this extension in my web application. I saw many videos including the yii framework web site and I am still confuse.

I changed the main.php according some pages but in every page I get an error, just like this: "include(MyEnum.php) - failed to open stream: No such file or directory"

Could someone help me so I can make that thing work in application?