The package offers strongly typed enums in PHP. In this package, enums are always objects, never constant values on their own. This allows for proper static analysis and refactoring in IDEs.
You can install the package via composer:
composer require tailflow/enum
Here is how enums are defined:
use Tailflow\Enum\Enum;
class Status extends Enum
{
public const Inactive = 0;
public const Active = 1;
public const OnHold = 3;
}
This is how they are used:
$class->setStatus(Status::Inactive);
By default, enum labels are derived from the constant names. To get enum label, you can use ::getLabel
method on enum class:
// $label will be equal to "OnHold" - the name of the constant
$label = Status::getLabel(Status::OnHold);
Optionally, you can provide a different label for any given enum value:
use Tailflow\Enum\Enum;
class Status extends Enum
{
public const Inactive = 0;
public const Active = 1;
public const OnHold = 3;
public static function labels(): array
{
return [
self::OnHold => 'waiting'
];
}
}
// $label will be equal to "waiting" - the custom label defined in "labels" method
$label = Status::getLabel(Status::OnHold);
To get a list of all labels of the enum, you can use ::getLabels
method:
// $labels will contain the array - ['Inactive', 'Active', 'waiting']
$labels = Status::getLabels();
To get a list of all values of the enum, you can use ::getValues
method:
// $labels will contain the array - [0, 1, 3]
$labels = Status::getValues();
The Laravel Orion is open-source software licensed under the MIT license.