commerceguys / enum
A PHP 5.4+ enumeration library.
Installs: 1 809 224
Dependents: 8
Suggesters: 0
Security: 0
Stars: 96
Watchers: 8
Forks: 3
Open Issues: 2
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is auto-updated.
Last update: 2024-11-25 07:02:55 UTC
README
A PHP 5.4+ enumeration library.
Class constants are frequently used to denote sets of allowed values. By grouping them in an enumeration class, we gain the ability to add helper methods, list all possible values and validate values against them.
A commerceguys/addressing example:
namespace CommerceGuys\Addressing\Enum; use CommerceGuys\Enum\AbstractEnum; /** * Enumerates available locality types. */ final class LocalityType extends AbstractEnum { const CITY = 'city'; const DISTRICT = 'district'; // We can provide a getDefault() method here, or anything else. } LocalityType::getAll(); // ['CITY' => 'city', 'DISTRICT' => 'district'] LocalityType::getKey('city'); // 'CITY' LocalityType::exists('city'); // true LocalityType::assertExists('invalid value'); // InvalidArgumentException LocalityType::assertAllExist(['district', 'invalid value']); // InvalidArgumentException
Meanwhile, on the AddressFormat:
// The AddressFormatInterface is now free of LOCALITY_TYPE_ constants. class AdressFormat implements AddressFormatInterface { public function setLocalityType($localityType) { LocalityType::assertExists($localityType); $this->localityType = $localityType; } }
The reason why this library was made instead of reusing myclabs/php-enum was that we didn't want to allow enumerations to be instantiated.