定制 rexlabs/enum 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

rexlabs/enum

Composer 安装命令:

composer require rexlabs/enum

包简介

Enumeration (enum) implementation for PHP

README 文档

README

Warning If you are using PHP 8.1 or higher, we recommend you use native php enums in place of this package.

We may release some maintenance patches but support for this package is otherwise being discontinued.

Feel free to fork our code and adapt it to your needs.

Enum PHP Library

License: MIT Packagist

Overview

This library provides an Enum / Enumeration implementation for PHP.

Why use this library

  • Very simple to implement and use.
  • Complex can optionally be mapped by providing a map() method.
  • Allows type-hinting when passing enumerated values between methods and classes.

Usage

First create a new class that extends \Rexlabs\Enum\Enum and do the following;

  1. Declare your constants
  2. Optional: provide a map() method:

Example

<?php

namespace Rexlabs\Enum\Readme;

use Rexlabs\Enum\Enum;

/**
 * Class City
 *
 * @package Rexlabs\Enum\Readme
 *
 * @method static static BRISBANE()
 * @method static static MELBOURNE()
 * @method static static SYDNEY()
 */
class City extends Enum
{
    const BRISBANE = 'Brisbane';
    const MELBOURNE = 'Melbourne';
    const SYDNEY = 'Sydney';
    
    // OPTIONAL - Provide a map() method if you would like to
    // map additional data, which will be available from the ->value() method
    public static function map(): array 
    {
        return [
            self::BRISBANE => ["state"=>"QLD", "population"=>""],
            self::MELBOURNE => ["state"=>"VIC", "population"=>"5m"],
            self::SYDNEY => ["state"=>"NSW", "population"=>"5m"],
        ];
    }
    
}

// Static access
echo City::BRISBANE;                 // "Brisbane"
echo City::MELBOURNE;                // "Melbourne"
City::names();                       // (array)["BRISBANE", "BRISBANE", "SYDNEY"]
City::keys();                        // (array)["Brisbane", "Melbourne", "Sydney"]
City::keyForName('BRISBANE');        // "Brisbane"
City::nameForKey('Melbourne');       // "MELBOURNE"
City::isValidKey('Sydney');          // (boolean)true
City::isValidKey('Paris');           // (boolean)false
               
// Getting an instance - all return a City instance.
$city = City::BRISBANE();                   
$city = City::instanceFromName('BRISBANE'); 
$city = City::instanceFromKey('Brisbane');

// Working with an instance
$city->name();                       // "BRISBANE"
$city->key();                        // "Brisbane"
$city->value()['population'];        // null - no value mapped
$city->is(City::BRISBANE);           // (boolean)true
$city->is(City::BRISBANE());         // (boolean)true
$city->is(City::SYDNEY());           // (boolean)false
$city->isNot(City::SYDNEY());        // (boolean)true
$city->isAnyOf([City::BRISBANE()]);  // (boolean)true
$city->isNoneOf([City::BRISBANE()]); // (boolean)false

// Or ...
City::SYDNEY()->key();               // "Sydney"
City::SYDNEY()->value();             // (array)["state"=>"NSW", "population"=>"5m"] 

Dependencies

  • PHP 7.0 or above.

Installation

To install in your project:

composer require rexlabs/enum

Type-hinting

Now you can type-hint your Enum object as a dependency:

<?php
function announceCity(City $city) {
    echo "{$city->key()} is located in {$city->value()["state"]}, population: {$city->value()["population"]}\n";
}

// Get a new instance
announceCity(City::SYDNEY());      // "Sydney is located in NSW, population: 5m"

Instance Methods

Each instance of Enum provides the following methods:

name()

Returns the constant name.

$enum->name();

key()

Returns the value/key assigned to the constant in the const MY_CONST = 'key' declaration.

$enum->key();

value()

Returns the value (if-any) that is mapped (in the array returned by map()). If no value is mapped, then this method returns null.

$enum->value();

is(Enum|string $compare)

Returns true if this instance is the same as the given constant key or enumeration instance.

$enum->is(City::SYDNEY);       // Compare to constant key
$enum->is(City::SYDNEY());     // Compare to instance

__toString()

The __toString() method is defined to return the constant name.

(string)City::SYDNEY();      // "SYDNEY"

Static Methods

map()

Returns an array which maps the constant keys to a value. This method can be optionally implemented in a sub-class. The default implementation returns an array of keys mapped to null.

instances()

Returns an array of Enum instances.

keys()

Returns an array of constant keys.

values()

Returns an array of values defined in map(). If map() is not implemented then an array of null values will be returned.

names()

Returns an array of all the constant names declared with the class.

namesAndKeys()

Returns an associative array of CONSTANT_NAME => key, for all the constant names declared within the class.

keyForName(string $name)

Returns the key for the given constant name.

nameForKey(string $key)

Returns the constant name for the given key (the inverse of keyForName).

valueForKey(string $key)

Returns the value (or null if not mapped) for the given key (as declared in the map() method).

keyForValue(mixed $value)

Returns the key for the given value (as declared in the map() method).

Note: If duplicate values are contained within the map() method then only the first key will be returned.

instanceFromName($name)

Create instance of this Enum from the given constant name.

instanceFromKey($key)

Create instance of this Enum from the given key.

isValidKey(string $key)

Returns true if the given key exists.

isValidName(string $name)

Returns true if the given constant name (case-sensitive) has been declared in the class.

requireValidKey(string $key)

Throws a \Rexlabs\Enum\Exceptions\InvalidKeyException if the given key does NOT exist.

Tests

To run tests:

composer tests

To run coverage report:

composer coverage

Coverage report is output to ./tests/report/index.html

Contributing

Contributions are welcome, please submit a pull-request or create an issue. Your submitted code should be formatted using PSR-1/PSR-2 standards.

About

  • Author: Jodie Dunlop
  • License: MIT
  • Copyright (c) 2018 Rex Software Pty Ltd

rexlabs/enum 适用场景与选型建议

rexlabs/enum 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 521.86k 次下载、GitHub Stars 达 47, 最近一次更新时间为 2018 年 03 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「library」 「enum」 「enumeration」 「constants」 「valuelist」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

围绕 rexlabs/enum 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

  • Stars: 47
  • Watchers: 5
  • Forks: 5
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-03-06