This small package can represent a enumeration field. For example in a database or an api.
Featureslist:
- inspired and mostly used for MySQL enum-fields or API enum-fields
- it is a simple string representation
- no other values are allow besides the defined in the class
- simple usage and easy to read
- no features a enum do not have to deal with
- with a default fallback value which will be used if no matching value exists in const´s
- you can harden this object by throwing an exception in the
getDefault
-method
- you can harden this object by throwing an exception in the
Basic install via composer
composer require freshp/php-enumeration
Take a look in tests/fixtures
to see a executable example.
Create a new object with:
- public const´s which represent strings
- implement the
getDefault
-method
use FreshP\PhpEnumeration\Enum;
class EnumExample extends Enum
{
public const TEST_CONSTANT = 'constant';
public const TEST_DEFAULT = 'default';
protected function getDefault(): string
{
return self::TEST_DEFAULT;
}
}
use annotations for better ide support
use FreshP\PhpEnumeration\Enum;
/**
* @method static self TEST_CONSTANT()
* @method static self TEST_DEFAULT()
*/
class EnumExample extends Enum
...
make the data of the parent toArray
-method public if you need to iterate over all options
class EnumExample extends Enum
{
...
public static function listAllOptions(): array
{
return self::toArray();
}
...
-
create the object by static call
$enum = EnumExample::TEST_CONSTANT();
-
create the object by normal initialization
$enum = new EnumExample(EnumExample::TEST_CONSTANT);
-
create a default object (the value from the
getDefault
-method will be called)$enum = new EnumExample();
-
compare the object by using the
__toString
-method$enum->__toString() === EnumExample::TEST_CONSTANT
or
$enum->isEqual(EnumExample::TEST_CONSTANT())
Run each command in the project root directory.
run all check with composer script
composer quickcheck
./vendor/bin/phpunit.phar --testdox
./vendor/bin/phpcbf.phar
./vendor/bin/phpcs.phar
./vendor/bin/phpstan.phar analyse -l max ./src