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.