An enumerated type (Enum) is a data type that consists of a set of predefined values. This can be useful for ensuring data consistency. The Enumerated package provides a simple base class for creating enumerated types allowing the devloper to define values statically.
Via Composer
$ composer require davidianbonner/enumerated
Most applications require some form of an enumerated type. PHP does not have native Enum support (yet: https://wiki.php.net/rfc/enum). To get past this, we tend to pack groups of predefined values into config or settings files as arrays. This doesn't represent the data or it's type in a straightforward manner.
<?php
return [
'language' => [
'php' => 'php',
'javascript' => 'js',
'css' => 'css',
'go' => 'go',
],
];
Used like so:
$codebase->language = config('language.php');
// or
foreach (config('language') as $language) {
echo '<option value="'.$language.'">'.$language.'</option>';
}
An enum would be a better fit for this set of values.
<?php
use DavidIanBonner\Enumerated\Enum;
class Language extends Enum
{
const PHP = 'php';
const JAVASCRIPT = 'js';
const GO = 'go';
const CSS = 'css';
}
Used like so:
$codebase->language = Language::PHP;
// or
$type = Language::PHP;
$codebase->language = Language::ofType($type)->value();
// or
foreach (Language::allValues() as $language) {
echo '<option value="'.$language.'">'.$language.'</option>';
}
A value can be validated against the predefined values:
if (Language::isValid($value)) {
// Is valid
}
This package requires the Laravel Support package in order to return a collection of the available values:
// Returns an instance of Illuminate\Support\Collection
Language::collect();
The allValues
and collect
method will accept a boolean argument to return the keys/constant names:
$values = Language::allValues(true);
// Returns
[
'PHP' => 'php',
'JAVASCRIPT' => 'js',
'CSS' => 'css',
'GO' => 'go',
]
Please see CHANGELOG for more information on what has changed recently.
$ phpunit test
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.