Download the PHP package joskolenberg/enum without Composer
On this page you can find all versions of the php package joskolenberg/enum. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download joskolenberg/enum
More information about joskolenberg/enum
Files in joskolenberg/enum
Informations about the package enum
Enum
Enum implementation for PHP
Installing
Use composer to pull this package in.
With Composer
Usage
Setting up an enum
An enum can be created by extending the JosKolenberg\Enum\Enum class.
This created class acts as the repository via static methods as well as the enum itself.
There are two abstract methods which have to be implemented. Use the seed method to populate the class with Enums, and tell the class which attribute identifies the enums by returning the name of this attribute in the identifierAttribute method.
An example implementation would be:
Next, the class can be designed like way you would any other.
Repository
The class offers the following static "repository-like" methods:
get()
return the enum with the given identifier.random()
return a random identifier (e.g. for seeding).collection()
return an Illuminate\Support\Collection containing all enums.identifiers()
return an Illuminate\Support\Collection containing only the identifiers for the enums.exists()
tell if an enum with the given identifier exists.
Enums are also available using a magic method with the same name as the identifier. e.g. UserType::get('dev')
equals UserType::dev()
Enum
The enum itself has the following methods:
identifier()
return the identifier value (e.g. 'dev' or 'admin' in the previous example) of this instance.equals(Enum $enum)
check if the given enum matches the current.
All defined attributes are by default available as read-only:
$value = $userType->value
passes.$userType->value = 'changed'
fails.
Custom Classes
If different enums of the same type should have different behaviour you can extend the base enum to more specific ones.
If you wish to extend the functionality of the collection, you can assign your own custom collection to your enum using the static newCollection method.
Pre-defined Enums
Because enums are usually no more than an identifier and maybe a display value, two pre-defined enums are available to extend.
Extend EnumWithId for an enum with only an id attribute:
Or extend EnumWithIdAndName for an enum with an id and name attribute:
Or create your own baseclass if you wish for different attributes on all of your enums.
Happy coding!
Jos Kolenberg [email protected]