That would ultimately depend on the amount of enums and the possible categorization of them.
You dont want to create any god classes in this (class that handles just about anything)
so you might start out with something like:
Class FormEnumeration {
protected static $enums = [
'field1' => [
'0' => 'No',
'1' => 'Yes',
'2' => 'FileNotFound' // joking
],
'role' => [
'1' => 'Employe',
'2' => 'Manager',
'3' => 'CEO',
'4' => 'Product Owner',
]
];
public static function toString($fieldName, $int)
{
if(!isSet(self::$enums[$fieldName])) {
Throw new \Exception($fieldName .' is not listed in enums');
}
if(!isSet(self::$enums[$fieldName][$int])) {
Throw new \Exception($int .' is not a valid integer for field '. $fieldName);
}
return self::$enums[$fieldName][$int]
}
public static function toInteger($fieldName, $value)
{
if(!isSet(self::$enums[$fieldName])) {
Throw new \Exception($fieldName .' is not listed in enums');
}
$key = array_search($value, self::$enums[$fieldName]);
if($key === false) {
Throw new \Exception($value .' is not a valid value for field '. $fieldName);
}
return $key;
}
}
And you could use it in the job model as such:
Class Job extends Model {
public function getRoleAttribute($roleId)
{
return FormEnumeration::toString('role', $roleId);
}
public function setRoleAttribute($roleName)
{
$this->attributes['role'] = FormEnumeration::toInteger('role', $roleName);
}
}
This would save integers to the DB, and when you ask for an attribute, it will translate it via the FormEnumeration class.
When the class gets too big, you can set it up to handle things differently from within the FormEnumeration Class, for instance by delegating it to different classes for each field:
Class FormEnumeration {
public static function toString($fieldName, $int)
{
$className = self::getClassName($fieldName);
return $className::toString($int);
}
public static function toInteger($fieldName, $value)
{
$className = self::getClassName($fieldName);
return $className::toString($value);
}
public static function getClassName($fieldName)
{
$className = ucfirst($fieldName) . 'FieldEnumeration';
if(!class_exists($className)) {
Throw new \Exception('There is no enumeration class for field '. $fieldName);
}
return $className;
}
}
Class RoleFieldEnumeration {
protected static $enums = [
'1' => 'Employe',
'2' => 'Manager',
'3' => 'CEO',
'4' => 'Product Owner',
];
public static function toString($int)
{
if(!isSet(self::$enums[$int])) {
Throw new \Exception('There is no value for '. $int .' in the Role field');
}
return self::$enums[$int]
}
public static function toInteger($value)
{
$key = array_search($value, self::$enums);
if($key === false) {
Throw new \Exception($value .' is not a valid value for field Role');
}
return $key;
}
}
Creating a separate class for each field (or form, whatever works best in your situation)
The job model would stay the same as in the previous example, but the FormEnumeration class will delegate it to a field specific class where needed.