Download the PHP package cerbero/laravel-enum without Composer
On this page you can find all versions of the php package cerbero/laravel-enum. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download cerbero/laravel-enum
More information about cerbero/laravel-enum
Files in cerbero/laravel-enum
Package laravel-enum
Short Description Laravel package to supercharge enum functionalities.
License MIT
Homepage https://github.com/cerbero90/laravel-enum
Informations about the package laravel-enum
๐ฒ Laravel Enum
Laravel package to supercharge enum functionalities.
[!TIP] Need a framework-agnostic solution? Consider using ๐ฒ Enum instead.
๐ฆ Install
Via Composer:
๐ฎ Usage
- ๐ท๏ธ Meta
- ๐งบ Cases collection
- ๐ช Magic translation
- ๐ Encapsulation
- ๐๏ธ Cache
- ๐ Session
- ๐ฆพ Artisan commands
- ๐๏ธ enum:annotate
- ๐๏ธ enum:make
- ๐ enum:ts
This package provides all the functionalities of ๐ฒ Enum plus Laravel-specific features.
To supercharge our enums, we just need to let them use the Enumerates trait:
๐ท๏ธ Meta
Laravel Enum extends Enum's meta by allowing us to attach meta with a class name. This class is resolved by the Laravel container when invoking the corresponding meta method:
In the enum above, each case specifies a handler meta with a class name. When a case calls its handler() meta method, the corresponding class is resolved through the IoC container:
If we need to resolve a default class for most cases, we can attach the meta to the enum itself. Cases with their own meta override the default class:
In the example above, all cases calling the handler() method resolve the DefaultPayoutHandler class, except for the Sent case that resolves SentPayoutHandler.
If the class to be resolved is callable (i.e. it implements the __invoke() method), that class will be both resolved and executed:
In the enum above, each case specifies a handlePayout meta with a callable class. Calling handlePayout() resolves and invokes the class with any passed parameters.
If we need to run a default callable class for most cases, we can attach the meta to the enum itself. Cases with their own meta override the default callable class:
In the example above, all cases calling the handlePayout() method execute the DefaultPayoutHandler class, except for the Sent case, which runs the SentPayoutHandler.
[!TIP] Our IDE can autocomplete meta methods thanks to the
enum:annotatecommand.Class names in meta are annotated by identifying the common interface or parent class they share.
๐งบ Cases collection
The original cases collection has been extended for better integration with the Laravel framework.
The new cases collection implements the Illuminate\Contracts\Support\Arrayable and Illuminate\Contracts\Support\Jsonable contracts and it can be serialized into a JSON.
It also leverages the following Laravel traits:
Illuminate\Support\Traits\Conditionablefor conditional chaining of methodsIlluminate\Support\Traits\Macroablefor adding methods to the collection at runtimeIlluminate\Support\Traits\Tappablefor running custom logic while keeping method chaining
Additionally, the new collection enables us to dump() and dd() its cases:
Cases collection can be cast in an Eloquent model to store multiple cases in a single database column and then re-hydrate those cases back into a collection:
Once the cast is set, we can assign an array of names, values or cases to the cast property of the model and receive a cases collection when accessing the property:
The cases collection above is stored in the database as ["One","Two"] for a pure enum, or as [1,2] for a backed enum.
The cast also supports bitwise backed enums, so for instance, if we have a Permissions enum implementing the Bitwise contract:
and we cast the permissions property in our Eloquent model:
we can assign a bitwise value or an array of bitwise values/cases to the permissions property and receive a cases collection in return:
The cases collection above is stored in the database as 3, the result of the OR bitwise operator.
๐ช Magic translation
On top of Enum's magic, when a case calls an inaccessible method without a corresponding meta match, Laravel Enum assumes that we want to access a translation:
By default the translation key is resolved as enums.{enum namespace}.{case name}.{inaccessible method}. If customization is needed, we can adjust the translation key:
The above logic will resolve the translation key as custom.{enum namespace}.{case name}.{inaccessible method}.
Additionally, we can pass named arguments to replace placeholders within our translations:
Translations are accessible through enum operations as well:
[!TIP] Our IDE can autocomplete translation methods thanks to the
enum:annotatecommand.
๐ Encapsulation
Laravel Enum offers extra traits to encapsulate Laravel features that deal with keys. By defining keys as enum cases, we can leverage Laravel features without having to remember or repeat such keys.
The benefits of this approach are many:
- avoiding scattered, error-prone strings throughout the codebase
- preventing key misspellings
- enabling IDE autocompletion
- reviewing all application keys in a central location
- updating keys in one place rather than replacing all instances
๐๏ธ Cache
To encapsulate the Laravel cache, we can define a backed enum with all our cache keys and apply the EnumeratesCacheKeys trait:
The EnumeratesCacheKeys trait incorporates Enumerates, hence all the features of this package. We can now leverage all the Laravel cache methods by statically calling enum cases:
When calling cases statically, we can pass parameters to resolve dynamic keys. Such parameters replace the {...} placeholders in the cache keys:
๐ Session
To encapsulate the Laravel session, we can define a backed enum with all our session keys and apply the EnumeratesSessionKeys trait:
The EnumeratesSessionKeys trait incorporates Enumerates, hence all the features of this package. We can now leverage all the Laravel session methods by statically calling enum cases:
When calling cases statically, we can pass parameters to resolve dynamic keys. Such parameters replace the {...} placeholders in the session keys:
[!TIP] Our IDE can autocomplete case static methods thanks to the
enum:annotatecommand.
๐ฆพ Artisan commands
A handy set of Artisan commands is provided out of the box to interact with enums seamlessly.
Some commands generate enums or related files. If we want to customize such files, we can publish their stubs:
After publishing, the stubs can be modified within the stubs/laravel-enum directory, located at the root of our application.
Certain commands supports the --all option to reference all enums in our application. By default, enums are searched in the app/Enums directory, but we can scan other folders as well:
In the example above, enums are searched in the app/Enums directory and all Enums sub-directories within domain, such as domain/Posts/Enums, domain/Users/Enums, etc.
๐๏ธ enum:annotate
IDEs can autocomplete case static methods, meta methods, translations, etc. by running the enum:annotate command:
If we don't provide any argument, a prompt appears to choose which enums to annotate. Or, we can simply use the --all option to annotate all enums:
Alternatively, we can provide one or more enums directly to the enum:annotate command. Both slashes and quoted backslashes are acceptable for defining enum namespaces:
Lastly, if we wish to overwrite existing method annotations on enums, we can include the --force option:
๐๏ธ enum:make
The enum:make command allows us to create a new, automatically annotated enum with the cases we need:
If no arguments are given, prompts will guide us through defining the enum namespace, backing type and cases. Otherwise, all these details can be typed via command line:
For creating backed enums, we can manually set custom values for each case:
Or, we can automatically assign values to cases by using the --backed option:
The --backed option accepts these values:
int0: assigns incremental integers starting from 0 (0, 1, 2...)int1: assigns incremental integers starting from 1 (1, 2, 3...)bitwise: assigns incremental bitwise values (1, 2, 4...)snake: assigns the case name in snake case (case_one, case_two...)kebab: assigns the case name in kebab case (case-one, case-two...)camel: assigns the case name in camel case (caseOne, caseTwo...)lower: assigns the case name in lower case (caseone, casetwo...)upper: assigns the case name in upper case (CASEONE, CASETWO...)
To overwrite an existing enum, we can include the --force option:
We can generate the TypeScript counterpart of the newly created enum by adding the --typescript option:
๐ enum:ts
The ts command converts enums to their TypeScript equivalents, ensuring backend and frontend synchronization:
If we don't provide any argument, a prompt appears to choose which enums to synchronize. Or, we can simply use the --all option to synchronize all enums:
Alternatively, we can provide one or more enums directly to the enum:ts command. Both slashes and quoted backslashes are acceptable for defining enum namespaces:
By default, enums are synchronized to resources/js/enums/index.ts, but this can be easily customized:
As shown above, we can either define a static path for TypeScript enums or dynamically set the TypeScript path for an enum based on its namespace.
To update enums that have already been synchronized, we can use the --force option:
๐ Change log
Please see CHANGELOG for more information on what has changed recently.
๐งช Testing
๐ Contributing
Please see CODE_OF_CONDUCT for details.
๐งฏ Security
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
๐ Credits
- Andrea Marco Sartori
- All Contributors
โ๏ธ License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-enum with dependencies
cerbero/enum Version ^2.3.2
illuminate/console Version >=9.0
illuminate/contracts Version >=9.0
illuminate/support Version >=9.0
laravel/prompts Version >=0.1