承接 isap-ou/laravel-enum-helpers 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

isap-ou/laravel-enum-helpers

Composer 安装命令:

composer require isap-ou/laravel-enum-helpers

包简介

Adding some helpers functions to PHP8 native enums for laravel projects

README 文档

README

This package brings some helpers to native PHP Enums

Laravel Enum Helpers Latest Version on Packagist Total Downloads

Installation

You can install the package via composer:

composer require isap-ou/laravel-enum-helpers

You will most likely need to edit the extensive configuration, so you can publish the config file with:

php artisan vendor:publish --tag="enum-helpers-config"

Default config

return [
    'enum_locations' => [
        'app/Enums' => '\\App\\Enums\\',
    ],

    'label' => [
        'prefix' => null,
        'namespace' => null,
    ],

    'post_migrate' => true,

    'js_objects_file' => 'resources/js/enums.js',
];
  1. enum_locations - path where enums located. Key is directory with enums, value - namespace for specified directory
  2. post_migrate - enable or disable post migrate event listener
  3. js_objects_file - path for generated js output
  4. label.prefix - get default prefix for translations of enum fields
  5. label.namespace - get default prefix for translations of enum namespace (when using as part of own package)

Available helpers

Migration helper

The way easy to add all enums to database column.

Just add to Enum trait InteractWithCollection

use IsapOu\EnumHelpers\Concerns\InteractWithCollection;

enum ExampleEnum: string
{

    use InteractWithCollection;

    case ENUM_ONE = 'enum_one';
    case ENUM_TWO = 'enum_two';
}

And in migration class

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('table_name', function (Blueprint $table){
            ...
            $table->enum('enum_column', ExampleEnum::values()->toArray());
            ...
        });
    }
}

Update enum columns in DB

Artisan command allows update available(possible) values for specific enum column.

Modify enum:

use IsapOu\EnumHelpers\Contracts\UpdatableEnumColumns;

enum ExampleEnum: string implements UpdatableEnumColumns
{

    case ENUM_ONE = 'enum_one';
    case ENUM_TWO = 'enum_two';
    
    public static function tables(): array
    {
        return [
            'table_name' => 'enum_column'
        ];
    }
}

Set column defaults (optional)

You can instruct the migrator to set a DEFAULT for specific enum columns. If an enum class defines a static method tableColumnDefaults(), the command will append DEFAULT <value> to the generated SQL for the matching table_column keys.

    /**
     * Map "table_column" => enum case.
     * The migrator will generate "... DEFAULT '<case->value>'".
     *
     * @return array<string, self>
     */
    public static function tableColumnDefaults(): array
    {
        return [
            'orders_status'      => self::NEW,
            'order_items_status' => self::NEW,
        ];
    }

And run command

php artisan enum-helpers:migrate:enums

There is also a listener enabled by default that will run after a successful migration. To disable it edit enum-helpers.php:

<?php 
return [
    ...
    
    'post_migrate' => false,
    
    ...
]

Convert PHP Enums to JS objects

Artisan command allows generate js objects based on enums

Modify enum:

use IsapOu\EnumHelpers\Contracts\UpdatableEnumColumns;

enum ExampleEnum: string implements JsConvertibleEnum
{
    case ENUM_ONE = 'enum_one';
    case ENUM_TWO = 'enum_two';
}

And run command

php artisan enum-helpers:js:export

Output will

export const ExampleEnum = Object.freeze({ENUM_ONE: 'enum_one', ENUM_TWO: 'enum_two'})

You can specify output path in config enum-helpers.php

return [
    ...
    
    'js_objects_file' => 'resources/js/enums.js'
    
    ...
]

Label Helper

The Label helper allows you to transform an enum instance into a textual label, making it useful for displaying human-readable, translatable enum values in your UI.

use IsapOu\EnumHelpers\Concerns\HasLabel;

enum ExampleEnum: string
{
    use HasLabel;

    case ENUM_ONE = 'enum_one';
    case ENUM_TWO = 'enum_two';
}

You can retrieve a textual label for an enum case using the getLabel method:

ExampleEnum::ENUM_ONE->getLabel()

By default, the getLabel method attempts to find a translation key, following this format: ExampleEnum.ENUM_ONE. 1. ExampleEnum - The class name of the enum. 2. ENUM_ONE - The enum case name.

Parameters

The getLabel method accepts three optional parameters: 1. prefix: Prepends a prefix to the translation key. 2. namespace: Prepends a namespace to the translation key. This is particularly useful when developing packages. 3. locale: Allows you to specify the locale for translation. If not provided, the app’s default locale will be used.

Example with custom parameters:
ExampleEnum::ENUM_ONE->getLabel('custom_prefix', 'custom_namespace', 'fr');

This will retrieve the French (fr) translation with the specified prefix and namespace.

getLabels Method

The getLabels method returns a collection of labels for all enum cases, making it convenient to retrieve or display translatable labels for multiple enum values at once.

$labels = ExampleEnum::getLabels();

// Output:
// Illuminate\Support\Collection {#1234
//     all: [
//         "ENUM_ONE" => "Enum One Label",
//         "ENUM_TWO" => "Enum Two Label",
//     ],
// }
Customizing Prefix, Namespace, and Locale

You can customize the prefix, namespace, and locale for the translations when retrieving labels for all cases:

$customLabels = ExampleEnum::getLabels('custom_prefix', 'custom_namespace', 'fr');

Global Configuration for Prefix and Namespace

You can define the prefix and namespace globally in the configuration file enum-helpers.config, or override them on the enum level by defining the following methods:

protected function getPrefix(): ?string
{
    return 'prefix';
}

protected function getNamespace(): ?string
{
    return 'namespace';
}

The global or per-enum configurations will be used unless you provide custom values when calling getLabel or getLabels.

Optional. Interface \IsapOu\EnumHelpers\Contracts\HasLabel for better IDE support

For better IDE support, you can implement the \IsapOu\EnumHelpers\Contracts\HasLabel interface. This helps provide autocomplete suggestions and improves code hinting for the getLabel method when working with enums.

FilamentPHP Compatibility

This helper is fully compatible with Enums in FilamentPHP

use Filament\Support\Contracts\HasLabel;

enum ExampleEnum: string implements HasLabel
{
    use HasLabel;

    case ENUM_ONE = 'enum_one';
    case ENUM_TWO = 'enum_two';
}

Contributing

Please, submit bugs or feature requests via the Github issues.

Pull requests are welcomed!

Thanks!

License

This project is open-sourced software licensed under the MIT License.

You are free to use, modify, and distribute it in your projects, as long as you comply with the terms of the license.

Maintained by ISAPP and ISAP OÜ.
Check out our software development services at isap.me.

isap-ou/laravel-enum-helpers 适用场景与选型建议

isap-ou/laravel-enum-helpers 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.11k 次下载、GitHub Stars 达 5, 最近一次更新时间为 2024 年 10 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 isap-ou/laravel-enum-helpers 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 isap-ou/laravel-enum-helpers 我们能提供哪些服务?
定制开发 / 二次开发

基于 isap-ou/laravel-enum-helpers 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2.11k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 5
  • 点击次数: 2
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 0
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-10-22