I am working on an app and I am considering an upgrade to PHP 8.1 and refactoring to make use of PHP Enums to match my DB Enums. I am curious what would be a recommended structure for storing them?
Would I create an app\enums folder? Or maybe use app\models? Or something else? Curious what others thoughts on this are. Personally I am leaning towards app\models since the puspose of Enums is to model data, but I am not sure if there is a structure that would be considered better?
If I am using an enum as part of a migration, I tend to declare the array of items as a constant in the top of its related model and reference that array in the migration.
E.g.
// Foo Model
public const STATUSES = [‘foo’, ‘bar’];
And then use as
Foo::STATUSES;
That approach allows me to use same array for validation before saving to that model.
TBH unless it’s just something simple like declaring a models status I’d prefer just to use a related model and set up a hasOne relationship.
Btw I realise I’ve missed your point about using php enums but this approach may anyway
@x7ryan i haven’t begun implementing them (the php8 way) but for laravel I think I’d go with app/enum but as always I think it depends. So much is preference. Like Automica until now I’ve done them on model.
<?php
namespace App\Enums;
use App\Enums\Exceptions\EnumNotFoundProperty;
use App\Enums\Exceptions\EnumUnAuthorisedValue;
abstract class Enum {
public function __construct(protected mixed $value)
{
}
private static function getProperty($name)
{
$property = static::class."::".strtoupper($name);
if(defined($property))
return constant($property);
throw new EnumNotFoundProperty($property);
}
public static function __callStatic(string $name, array $arguments)
{
return static::getProperty($name);
}
public static function fromKey(string $key):Enum
{
return new static( static::getProperty($key) );
}
public static function fromValue(mixed $value)
{
if(!in_array($value, array_values(static::getConstants()) ) )
throw new EnumUnAuthorisedValue($value);
return new static($value);
}
private static function getConstants() {
$enumClass = new \ReflectionClass(static::class);
return $enumClass->getConstants();
}
public function __toString():string
{
return (string)$this->value;
}
public function equal(mixed $value):bool
{
return $this->value === $value;
}
public function getValue()
{
return $this->value;
}
}