
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;
}
该接口定义了三个方法:
我们可以通过使用特征来封装从枚举案例生成选项的通用逻辑来进一步增强我们的枚举。这就是 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' => $case->value,
'label' => $case->label(),
'description' => $case->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 => 'running',
self::stopped => 'stopped',
self::failed => 'failed',
default => throw new \exception('unknown enum value requested for the label'),
};
}
public function description(): string
{
return match ($this) {
self::pending => 'the server is currently being created or initialized.',
self::running => 'the server is live and operational.',
self::stopped => 'the server is stopped but can be restarted.',
self::failed => 'the server encountered an error and is not running.',
default => throw new \exception('unknown enum value requested for the description'),
};
}
}
如果您正在处理多个枚举,并且想要一种快速的方法来设置它们具有类似的功能,您可以使用一个可重用的存根,它结合了我们所涵盖的所有内容。这是此类存根的改进版本:
<?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 => throw new \exception('unknown enum value requested for the label'),
};
}
public function description(): string
{
return match ($this) {
self::example => 'this is an example description.', // add descriptions for other cases
default => throw new \exception('unknown enum value requested for the description'),
};
}
}
让我们添加一个示例,说明如何在 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' => 'pending', 'label' => 'pending installation', 'description' => 'the server is currently being created or initialized.'],
['value' => 'running', 'label' => 'running', 'description' => 'the server is live and operational.'],
// other cases...
]
在 blade 模板中,您现在可以使用 statusoptions 填充选择下拉列表并在用户选择状态时显示说明。
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Edit Server</h1>
<form action="{{ route('servers.update', $server->id) }}" 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'] }}"
@if ($server->status === $option['value']) selected @endif>
{{ $option['label'] }}
</option>
@endforeach
</select>
</div>
<div id="statusDescription" class="alert alert-info">
<!-- Default description when the page loads -->
{{ $statusOptions[array_search($server->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
控制器:在控制器中调用 serverstatus::options() 方法来生成选项数组,然后将其传递到 blade 视图。
刀片模板:
javascript:使用 @json 指令将 statusoptions 数组传递给 javascript,每当用户更改所选状态时 updatedescription() 函数都会更新描述。
此设置以用户友好的方式使用枚举选项,利用枚举中的标签和描述方法,在表单中提供丰富的体验。
通过将 php 枚举与接口和特征相结合,您可以创建一个灵活、可扩展且可重用的模式,用于管理带有标签、描述和选择选项等附加逻辑的常量。即使应用程序的复杂性不断增加,这种设计也能确保整个代码库的一致性和可维护性。
通过我们构建的接口和特征结构,您现在可以以干净、有组织的方式实现枚举。无论您是处理服务器状态、用户角色还是支付状态,这种方法都将帮助您编写更清晰、更易于维护的代码。
编码愉快!
作者简介
nasrul hazim 是一位拥有超过 14 年经验的解决方案架构师和软件工程师。您可以在 github 上的 nasrulhazim 上探索他的更多作品。
以上就是使用接口和特征在 PHP 中编写灵活的枚举的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号