zvermafia/larastate
Composer 安装命令:
composer require zvermafia/larastate
包简介
A convenient way to access entity states' values and their localizations.
README 文档
README
Easy access to entity states values and to their localizations.
Navigation by sections
Introduction
The problem
When you have an entity with some states you usually need to access to those states' values and to their localizations. Let's consider the following cases:
Let's assume we have a User entity with a role state. And the role state can only accept 'member', 'moderator' and 'administrator' values.
-
When you need to validate a state's acceptable values. So when we try to create a new user we need to validate the role state value. But how to do it if we don't have a main source for that values? And usually we may do like below:
/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ // ... other validation rules 'role' => [ 'required', Rule::in(['member', 'moderator', 'administrator']), // 🙁 values are hardcoded ], ]; }
-
When you need to display localization for one of the state's values. For example when you need to give an information about a user's role:
<li>{{ $user->name }}</li> <li>{{ $user->email }}</li> <li>{{ trans("user.states.role.{$user->role}") }}</li>🙁 Localization file path, file name and locale key are hardcoded.
-
When you need to display those values with locales. For example in a select box:
@foreach (['member', 'moderator', 'administrator'] as $value) <option value="{{ $value }}">@lang("user.states.role.{$value}")</option> @endforeach
🙁 Hardcoded, hardcoded, ...
And yes when you hardcoded those values in different places of your project then it will be harder to change (add, remove, rename) those values. Because you don't use a main source for those values.
A solution
Unfortunately Laravel doesn't provide a solution for this problem out of the box. So I've created this package. With this package you will not have problems in the above section! Let's solve those problems in the appropriate order.
Firstly create a States folder in the app directory, then create a UserState class in it with extending a StateAbstract abstract class. And define a ROLE constant in the class with those values from the above section. You should have something below:
<?php // app/States/UserState.php namespace App\States\UserState; use Zvermafia\Larastate\Abstracts\StateAbstract; class UserState extends StateAbstract { /** @var array */ public const ROLE = [ 'member' => 'member', 'moderator' => 'moderator', 'administrator' => 'administrator', ]; }
-
When you need to validate a state's acceptable values:
/** * Get the validation rules that apply to the request. * * @param \App\States\UserState $user_states * @return array */ public function rules(UserState $user_states) { return [ // ... other validation rules 'role' => [ 'required', Rule::in($user_states->getRoleValues()), // 🙂 values are not hardcoded! ], ]; }
-
When you need to display localization for one of the state's values. For example when you need to give an information about a user's role:
<li>{{ $user->name }}</li> <li>{{ $user->email }}</li> <li>{{ $user_states->getRoleLocale($user->role) }}</li>🙂 Localization file path, file name and locale key are taken from the single source!
-
When you need to display those values with locales. For example in a select box:
@foreach ($user_states->getRoleValuesWithLocales() as $value => $locale) <option value="{{ $value }}">{{ $locale }}</option> @endforeach
🙂 Much better!
Install
To install the package just pull it via composer and you're ready to setup.
$ composer require zvermafia/larastate
Setup
The package have some convention about structuring a state classes directory, naming those classes and naming constants. But all this can be changed to suit your needs by extending a StateAbstract abstract class. So if you need it then take a look at the source code.
- By default you should put all your state classes to
app/Statesdirectory. And yes usually there is not that directory so you need to create it by yourself. - And your state class names should end with
Statepostfix, for exampleUserState,PageState,OrderStateand so on... - Constant names should be in upper case and each word separated by underscore.
Let's assume we want to setup a state class for a post entity, so our steps are follows:
- Create a
Statesfolder in theappdirectory; - Create a
PostState.phpfile and put it into theapp/Statesdirectory; - Extend a
StateAbstractabstract class and define constants, you should have something below:<?php namespace App\States; use Zvermafia\Larastate\Abstracts\StateAbstract; class PostState extends StateAbstract { /** @var array */ public const STATUS = [ 'draft' => 0, 'published' => 1, ]; /** @var array */ public const TYPE = [ 'info' => 0, 'blog' => 1, 'news' => 2, ]; }
- Create localization file in a
resources/lang/en/entitiesdirectory with the entity name, so in our case it will bepost.php. It's a regular Laravel's localization file but by default all state localizations should be grouped in astatekey of the array. So you should have something like below:<?php // resources/lang/en/entities/post.php return [ // here's other localization like attribute/property... 'state' => [ 'status' => [ App\States\PostState::STATUS['draft'] => 'Draft', App\States\PostState::STATUS['published'] => 'Published', ], 'type' => [ App\States\PostState::TYPE['info'] => 'Static page', App\States\PostState::TYPE['blog'] => 'Blog post', App\States\PostState::TYPE['news'] => 'News post', ], ], ];
Usage
For usage example we will use our PostState which we created it in the above section.
There are three cases and all works through PHP's magic __call() method:
- Getting values for the state
- Getting values with locales for the state
- Getting a locale for one of the state's values
All methods start with prefix get and ends with one of the case names (Values, ValuesWithLocales or Locale).
And between those prefix and postfixes you should write your state name in StudlyCase format.
For a type state those will be:
getTypeValues()getTypeValuesWithLocales()getTypeLocale(1)
$post_states = new App\States\PostState(); $post_states->getTypeValues(); // [0, 1, 2] $post_states->getTypeValuesWithLocales(); // [0 => 'Static page', 1 => 'Blog post', 2 => 'News post'] $post_states->getTypeValues(); // 'Blog post'
Alternatives
- BenSampo/laravel-enum
- artkonekt/enum-eloquent
- nasyrov/laravel-enums
- mad-web/laravel-enum
- spatie/laravel-enum
- cerbero90/laravel-enum
So why I've created this package when there is already such kind of packages? Because they are a bit complicated for my simple task.
Change log
Please see CHANGELOG for more information on what has changed recently.
Testing
$ composer test
Contributing
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
Security
If you discover any security related issues, please email mohirjon@gmail.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
zvermafia/larastate 适用场景与选型建议
zvermafia/larastate 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11 次下载、GitHub Stars 达 0, 最近一次更新时间为 2020 年 03 月 01 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「package」 「state」 「enum」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 zvermafia/larastate 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 zvermafia/larastate 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 zvermafia/larastate 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Doctrine implementation of the MetaborStd (Statemachine) for PHP 8.2+
Enum type behavior for Yii2 based on class constants
A PHP Abstract Enum Class
A simple state dropdown field for SilverStripe forms
Compatibility layer for emulating enumerations in PHP < 8.1 and native enumerations in PHP >= 8.1
Enum type behavior and helper for Yii2, for PostgreSQL only
统计信息
- 总下载量: 11
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 15
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2020-03-01