2024-10-11

使用接口和特征在 PHP 中编写灵活的枚举

使用接口和特征在 php 中编写灵活的枚举

php 枚举是一个强大的工具,用于定义一组固定的常量,同时使您能够将功能附加到这些常量。除了简单地保存值之外,枚举还可以实现接口并使用特征来扩展其功能。这使得它们在复杂的应用程序中更加灵活和可重用。

在这篇文章中,我们将通过将枚举与接口和特征相结合,将您的 php 枚举设计提升到一个新的水平。我们将了解如何创建提供标签、描述的枚举,甚至为表单中的选择输入生成选项。最后,您将拥有一个可重用的结构,可以轻松扩展并在所有枚举中保持一致的行为。

为什么将枚举与接口和特征一起使用?

枚举非常适合表示状态、状态或类型。然而,仅仅拥有一个常量列表通常是不够的。在许多情况下,您可能需要:

  • 每个枚举案例的描述性标签或人类可读的名称。
  • 详细描述解释每个枚举案例的含义。
  • 用户界面中选择输入的结构化选项。

通过实现接口和使用特征,您可以确保您的枚举是一致的、可扩展的并且能够适应不断变化的需求。

立即学习PHP免费学习笔记(深入)”;

创建枚举接口

我们将首先定义一个任何枚举都可以实现的接口,以确保它具有返回标签、描述和生成选择输入选项的方法。

界面如下:

<?php namespace app/contracts;

interface enum
{
    /**
     * get the label for the enum case.
     *
     * @return string
     */
    public function label(): string;

    /**
     * get the description for the enum case.
     *
     * @return string
     */
    public function description(): string;

    /**
     * generate an array of options with value, label, and description for select inputs.
     *
     * @return array
     */
    public static function options(): array;
}
登录后复制

该接口定义了三个方法:

  1. label:为每个枚举案例返回一个人类可读的名称。
  2. 描述:提供每个枚举案例的详细描述。
  3. options:生成一个选项数组,其中每个选项包含枚举的值、标签和描述。这在构建表单时非常有用。

利用可重用逻辑的特征

我们可以通过使用特征来封装从枚举案例生成选项的通用逻辑来进一步增强我们的枚举。这就是 interactswithenumoptions 特征的用武之地。

<?php namespace app/concerns;

trait interactswithenumoptions
{
    /**
     * generate an array of options with value, label, and description for select inputs.
     *
     * @return array
     */
    public static function options(): array
    {
        return array_map(fn ($case) => [
            'value' =&gt; $case-&gt;value,
            'label' =&gt; $case-&gt;label(),
            'description' =&gt; $case-&gt;description(),
        ], self::cases());
    }
}
登录后复制

此特征提供了一个可重用的 options() 方法,该方法循环遍历所有枚举案例 (self::cases()) 并返回一个数组,其中每个项目包含枚举案例的值、标签和描述。这在生成选择下拉选项时特别有用。

在枚举中实现接口和特征

现在让我们创建一个用于管理服务器状态的枚举。该枚举将实现 enum 接口并使用 interactswithenumoptions 特征来生成表单选项。

<?php namespace app/enums;

use app/contracts/enum as contract;
use app/concerns/interactswithenumoptions;

enum serverstatus: string implements contract
{
    use interactswithenumoptions;

    case pending = 'pending';
    case running = 'running';
    case stopped = 'stopped';
    case failed = 'failed';

    public function label(): string
    {
        return match ($this) {
            self::pending => 'pending installation',
            self::running =&gt; 'running',
            self::stopped =&gt; 'stopped',
            self::failed =&gt; 'failed',
            default =&gt; throw new /exception('unknown enum value requested for the label'),
        };
    }

    public function description(): string
    {
        return match ($this) {
            self::pending =&gt; 'the server is currently being created or initialized.',
            self::running =&gt; 'the server is live and operational.',
            self::stopped =&gt; 'the server is stopped but can be restarted.',
            self::failed =&gt; 'the server encountered an error and is not running.',
            default =&gt; throw new /exception('unknown enum value requested for the description'),
        };
    }
}
登录后复制

这里发生了什么?

  1. 枚举案例:我们定义了代表不同服务器状态的几种案例(例如,pending、running、stopped、failed)。
  2. 标签和描述方法:label() 和description() 方法为每个枚举案例提供人类可读的名称和详细描述。这些方法使用匹配语句将每个案例映射到其相应的标签和描述。
  3. 选项特征:interactswithenumoptions 特征用于自动生成表单选择输入的选项数组,其中包含案例的值、标签和描述。

通过可重用存根增加灵活性

如果您正在处理多个枚举,并且想要一种快速的方法来设置它们具有类似的功能,您可以使用一个可重用的存根,它结合了我们所涵盖的所有内容。这是此类存根的改进版本:

<?php namespace {{ namespace }};

use app/contracts/enum as contract;
use app/concerns/interactswithenumoptions;

enum {{ class }} implements contract
{
    use interactswithenumoptions;

    case example; // add actual cases here

    public function label(): string
    {
        return match ($this) {
            self::example => 'example label', // add labels for other cases
            default =&gt; throw new /exception('unknown enum value requested for the label'),
        };
    }

    public function description(): string
    {
        return match ($this) {
            self::example =&gt; 'this is an example description.', // add descriptions for other cases
            default =&gt; throw new /exception('unknown enum value requested for the description'),
        };
    }
}
登录后复制

自定义存根:

  • 将 {{ namespace }} 替换为枚举的实际命名空间。
  • 在 case 块内添加相关的枚举 case 并定义相应的标签和描述。

为什么这种模式有效

  1. 跨枚举的一致性:通过此设置,每个实现 enum 接口的枚举都必须提供标签和描述。这确保所有枚举都遵循相同的模式,使您的代码库更易于维护。
  2. 特征的可重用性:interactswithenumoptions特征封装了生成选项的通用逻辑,可以在多个枚举之间重用,而无需重复代码。
  3. 可扩展性:随着应用程序的增长,添加新的枚举案例或其他方法将成为一个无缝的过程。如果您需要修改选项的生成方式或添加新功能,您可以在特征或界面中集中执行此操作。

laravel blade 模板中的用法示例

让我们添加一个示例,说明如何在 laravel blade 模板中使用枚举。假设我们正在使用 serverstatus 枚举,并且希望使用 interactswithenumoptions 特征生成的选项生成一个选择输入,供用户选择服务器状态。

首先,确保您的控制器将枚举选项传递给视图。例如:

控制器示例:

<?php namespace app/http/controllers;

use app/enums/serverstatus;

class servercontroller extends controller
{
    public function edit($id)
    {
        $server = server::findorfail($id);
        $statusoptions = serverstatus::options(); // get enum options using the trait

        return view('servers.edit', compact('server', 'statusoptions'));
    }
}
登录后复制

serverstatus::options() 方法将返回一个具有以下结构的数组:

[
    ['value' =&gt; 'pending', 'label' =&gt; 'pending installation', 'description' =&gt; 'the server is currently being created or initialized.'],
    ['value' =&gt; 'running', 'label' =&gt; 'running', 'description' =&gt; 'the server is live and operational.'],
    // other cases...
]
登录后复制

刀片模板示例:

在 blade 模板中,您现在可以使用 statusoptions 填充选择下拉列表并在用户选择状态时显示说明。

@extends('layouts.app')

@section('content')
    <div class="container">
        <h1>Edit Server</h1>

        <form action="%7B%7B%20route('servers.update',%20%24server-&gt;id)%20%7D%7D" method="POST">
            @csrf
            @method('PUT')

            <!-- Other form fields -->

            <div class="mb-3">
                <label for="status" class="form-label">Server Status</label>
                <select name="status" id="status" class="form-control" onchange="updateDescription()">
                    @foreach ($statusOptions as $option)
                        <option value="{{ $option['value'] }}">status === $option['value']) selected @endif&gt;
                            {{ $option['label'] }}
                        </option>
                    @endforeach
                </select>
</div>

            <div id="statusDescription" class="alert alert-info">
                <!-- Default description when the page loads -->
                {{ $statusOptions[array_search($server-&gt;status, array_column($statusOptions, 'value'))]['description'] }}
            </div>

            <button type="submit" class="btn btn-primary">Update Server</button>
        </form>
    </div>

    <script>
        const statusOptions = @json($statusOptions);

        function updateDescription() {
            const selectedStatus = document.getElementById('status').value;
            const selectedOption = statusOptions.find(option => option.value === selectedStatus);
            document.getElementById('statusDescription').textContent = selectedOption ? selectedOption.description : '';
        }
    </script>
@endsection
登录后复制

解释:

  1. 控制器:在控制器中调用 serverstatus::options() 方法来生成选项数组,然后将其传递到 blade 视图。

  2. 刀片模板

    • 创建
    • 选择上的 onchange 事件会触发 updatedescription() javascript 函数,该函数会根据所选选项更新下拉列表下方的描述。
    • 最初,页面加载时会显示当前服务器状态的描述。
  3. javascript:使用 @json 指令将 statusoptions 数组传递给 javascript,每当用户更改所选状态时 updatedescription() 函数都会更新描述。

此设置以用户友好的方式使用枚举选项,利用枚举中的标签和描述方法,在表单中提供丰富的体验。

结论

通过将 php 枚举与接口和特征相结合,您可以创建一个灵活、可扩展且可重用的模式,用于管理带有标签、描述和选择选项等附加逻辑的常量。即使应用程序的复杂性不断增加,这种设计也能确保整个代码库的一致性和可维护性。

通过我们构建的接口和特征结构,您现在可以以干净、有组织的方式实现枚举。无论您是处理服务器状态、用户角色还是支付状态,这种方法都将帮助您编写更清晰、更易于维护的代码。

编码愉快!


作者简介

nasrul hazim 是一位拥有超过 14 年经验的解决方案架构师和软件工程师。您可以在 github 上的 nasrulhazim 上探索他的更多作品。

以上就是使用接口和特征在 PHP 中编写灵活的枚举的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1043769.html

发表回复

Your email address will not be published. Required fields are marked *