Laravel 包,用于增强枚举功能。
[![Author][ico-author]][link-author] [![PHP Version][ico-php]][link-php] [![Laravel Version][ico-laravel]][link-laravel] [![Latest Version][ico-version]][link-packagist] ![Software License][ico-license] [![Build Status][ico-actions]][link-actions] [![Code Quality][ico-code-quality]][link-code-quality] [![Coverage][ico-coverage]][link-coverage] [![PHPStan Level][ico-phpstan]][link-phpstan] [![Total Downloads][ico-downloads]][link-downloads]
Laravel package to supercharge enum functionalities.
[!TIP] Need a framework-agnostic solution? Consider using Enum instead.
Via Composer:
composer require cerbero/laravel-enumThis 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:
use Cerbero\LaravelEnum\Concerns\Enumerates;
enum Numbers: int
{
use Enumerates;
case One = 1;
case Two = 2;
case Three = 3;
}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:
use Cerbero\Enum\Attributes\Meta;
enum PayoutStatuses
{
use Enumerates;
#[Meta(handler: SentPayoutHandler::class)]
case Sent;
#[Meta(handler: OnHoldPayoutHandler::class)]
case OnHold;
#[Meta(handler: DeclinedPayoutHandler::class)]
case Declined;
}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:
// instead of this
$handler = match ($payout->status) {
PayoutStatuses::Sent => SentPayoutHandler::class,
PayoutStatuses::OnHold => OnHoldPayoutHandler::class,
PayoutStatuses::Declined => DeclinedPayoutHandler::class,
};
return Container::getInstance()->make($handler);
// we can do this
return $payout->status->handler();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:
use Cerbero\Enum\Attributes\Meta;
#[Meta(handler: DefaultPayoutHandler::class)]
enum PayoutStatuses
{
use Enumerates;
#[Meta(handler: SentPayoutHandler::class)]
case Sent;
case OnHold;
case Declined;
}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:
use Cerbero\Enum\Attributes\Meta;
enum PayoutStatuses
{
use Enumerates;
#[Meta(handlePayout: SentPayoutHandler::class)]
case Sent;
#[Meta(handlePayout: OnHoldPayoutHandler::class)]
case OnHold;
#[Meta(handlePayout: DeclinedPayoutHandler::class)]
case Declined;
}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.
// instead of this
$handler = match ($payout->status) {
PayoutStatuses::Sent => SentPayoutHandler::class,
PayoutStatuses::OnHold => OnHoldPayoutHandler::class,
PayoutStatuses::Declined => DeclinedPayoutHandler::class,
};
$handlePayout = Container::getInstance()->make($handler);
return $handlePayout($payout);
// we can do this
return $payout->status->handlePayout($payout);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:
use Cerbero\Enum\Attributes\Meta;
#[Meta(handlePayout: DefaultPayoutHandler::class)]
enum PayoutStatuses
{
use Enumerates;
#[Meta(handlePayout: SentPayoutHandler::class)]
case Sent;
case OnHold;
case Declined;
}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.
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\Conditionable for conditional chaining of methodsIlluminate\Support\Traits\Macroable for adding methods to the collection at runtimeIlluminate\Support\Traits\Tappable for running custom logic while keeping method chainingAdditionally, the new collection enables us to dump() and dd() its cases:
Numbers::collect()->dump();
Numbers::collect()->dd();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:
use Cerbero\LaravelEnum\CasesCollection;
class User extends Model
{
// before Laravel 11
protected $casts = [
'numbers' => CasesCollection::class . ':' . Numbers::class,
];
// after Laravel 11
protected function casts(): array
{
return [
'numbers' => CasesCollection::of(Numbers::class),
];
}
}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:
$user->numbers = ['One', 'Two'];
$user->numbers = [1, 2];
$user->numbers = [Numbers::One, Numbers::Two];
$user->numbers; // CasesCollection[Numbers::One, Numbers::Two]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:
use Cerbero\LaravelEnum\Contracts\Bitwise;
enum Permissions: int implements Bitwise
{
use Enumerates;
case CreatePost = 1;
case UpdatePost = 2;
case DeletePost = 4;
}and we cast the permissions property in our Eloquent model:
use Cerbero\LaravelEnum\CasesCollection;
class User extends Model
{
// before Laravel 11
protected $casts = [
'permissions' => CasesCollection::class . ':' . Permissions::class,
];
// after Laravel 11
protected function casts(): array
{
return [
'permissions' => CasesCollection::of(Permissions::class),
];
}
}we can assign a bitwise value or an array of bitwise values/cases to the permissions property and receive a cases collection in return:
$user->permissions = 3;
$user->permissions = 1 | 2;
$user->permissions = Permissions::CreatePost->value | Permissions::UpdatePost->value;
$user->permissions = [1, 2];
$user->permissions = [Permissions::CreatePost, Permissions::UpdatePost];
$user->permissions; // CasesCollection[Permissions::CreatePost, Permissions::UpdatePost]The cases collection above is stored in the database as 3, the result of the OR bitwise operator.
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:
Numbers::One->description();
// lang/en/enums.php
return [
Numbers::class => [
'One' => [
'description' => 'This is the case One.',
],
],
];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:
use Cerbero\LaravelEnum\Enums;
Enums::translateFrom(function(UnitEnum $case, string $method) {
return sprintf('custom.%s.%s.%s', $case::class, $case->name, $method);
});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:
return [
Numbers::class => [
'One' => [
'description' => 'This is the case :value.',
],
],
];
// This is the case 1.
Numbers::One->description(value: 1);Translations are accessible through enum operations as well:
$options = Numbers::pluck('description', 'value');
/*
[
1 => 'This is the case One.',
2 => 'This is the case Two.',
3 => 'This is the case Three.',
]
*/[!TIP] Our IDE can autocomplete translation methods thanks to the
enum:annotatecommand.
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:
To encapsulate the Laravel cache, we can define a backed enum with all our cache keys and apply the EnumeratesCacheKeys trait:
use Cerbero\LaravelEnum\Concerns\EnumeratesCacheKeys;
enum CacheKeys: string
{
use EnumeratesCacheKeys;
case PostComments = 'posts.{int $postId}.comments';
case Tags = 'tags';
case TeamMemberPosts = 'teams.{string $teamId}.users.{string $userId}.posts';
}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:
CacheKeys::TeamMemberPosts($teamId, $userId)->exists();To encapsulate the Laravel session, we can define a backed enum with all our session keys and apply the EnumeratesSessionKeys trait:
use Cerbero\LaravelEnum\Concerns\EnumeratesSessionKeys;
enum SessionKeys
{
use EnumeratesSessionKeys;
case CartItems = 'cart-items';
case OnboardingStep = 'onboarding-step';
case FormsData = 'forms.{int $formId}.data';
}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:
SessionKeys::FormsData($formId)->exists();[!TIP]
暂无开放 Issues,或尚未同步最近议题。