A simple and easy-to-use enumeration extension package to help you manage enumerations in your project more conveniently

Overview

constants

A simple and easy-to-use enumeration extension package to help you manage enumerations in your project more conveniently

  • 一个简单好用的枚举扩展包,帮助你更方便地管理项目中的枚举

本扩展包在 jiannei/laravel-enum 修改而来

介绍

asfop/constants 主要用来扩展项目中的常量使用,通过合理的定义常量可以使代码更加规范,更易阅读和维护。

当您需要定义错误码和错误信息时,可能会使用以下方式,



class ErrorCode
{
    const SERVER_ERROR = 500;
    const PARAMS_INVALID = 1000;

    public static $messages = [
        self::SERVER_ERROR => 'Server Error',
        self::PARAMS_INVALID => '参数非法'
    ];
}

$message = ErrorCode::messages[ErrorCode::SERVER_ERROR] ?? '未知错误';

但这种实现方式并不友好,每当要查询错误码与对应错误信息时,都要在当前 Class 中搜索两次,

概览

  • 提供了多种实用的方式来实例化枚举
  • 支持基于注解多语言本地化描述

安装

$ composer require "asfop/constants"

使用

更为具体的使用可以查看测试用例:https://github.com/g1012415019/constants/blob/main/tests

常规使用

  • 定义


use Asfop\Constants\Constant;

class ExampleConstant extends Constant
{
    /**
     * @message("登录")
     */
    const SIGN_IN = 0;
    /**
     * @message("注册")
     */
    const REGISTER = 1;
    /**
     * @message("找回密码")
     */
    const RETRIEVE_PASSWORD = 2;
    /**
     * @message("注销账号")
     */
    const CANCEL_ACCOUNT = 3;

//    /**
//     * 重写从注解里面拿到的Message
//     * @param mixed $description 描述
//     * @param mixed $key key
//     * @param mixed $value 值
//     * @return mixed
//     */
//    protected static function message($description, $key, $value)
//    {
//        return $description;
//    }

}
  • 使用
// 获取常量的值
ExampleConstant::SIGN_IN;// 0

// 获取所有已定义常量的名称
$keys = ExampleConstant::getKeys();// ['SIGN_IN ', 'REGISTER', 'RETRIEVE_PASSWORD ', 'CANCEL_ACCOUNT']

// 根据常量的值获取常量的名称
ExampleConstant::getKey(1);// REGISTER 

// 获取所有已定义常量的值
$values = ExampleConstant::getValues();// [0, 1, 2, 3]

// 根据常量的名称获取常量的值
ExampleConstant::getValue('REGISTER ');// 1
  • 本地化描述
// 返回中文描述
ExampleConstant::getDescription(ExampleConstant::CANCEL_ACCOUNT);// 注销账号

// 补充:也可以先实例化常量对象,然后再根据对象实例来获取常量描述
$responseEnum = new ExampleEnum(ExampleEnum::CANCEL_ACCOUNT);
$responseEnum->description;// 注销账号

// 其他方式
ExampleConstant::CANCEL_ACCOUNT()->description;// 注销账号
  • 枚举校验
// 检查定义的常量中是否包含某个「常量值」
ExampleConstant::hasValue(1);// true
ExampleConstant::hasValue(-1);// false

// 检查定义的常量中是否包含某个「常量名称」 

ExampleConstant::hasKey('CANCEL_ACCOUNT ');// true
ExampleConstant::hasKey('ACCOUNT ');// false
  • 枚举实例化:枚举实例化以后可以方便地通过对象实例访问枚举的 key、value 以及 description 属性的值。
// 方式一:new 传入常量的值
$administrator1 = new ExampleConstant(ExampleConstant::CANCEL_ACCOUNT);

// 方式二:fromValue
$administrator2 = ExampleConstant::fromValue(0);

Asfop\Tests\Constants\ExampleConstant Object
(
    [description] => 登录
    [key] => SIGN_IN
    [value] => 0
)

// 方式三:fromKey
$administrator3 = ExampleConstant::fromKey('CANCEL_ACCOUNT');

Asfop\Tests\Constants\ExampleConstant Object
(
    [description] => 注销账号
    [key] => CANCEL_ACCOUNT
    [value] => 3
)

// 方式四:magic
$administrator4 = ExampleConstant::CANCEL_ACCOUNT();

Asfop\Tests\Constants\ExampleConstant Object
(
    [description] => 注销账号
    [key] => CANCEL_ACCOUNT
    [value] => 3
)
  • toArray
$array = ExampleConstant::toArray();

/*
[
    'SIGN_IN' => 0,
    'REGISTER' => 1,
    'RETRIEVE_PASSWORD' => 2,
    'CANCEL_ACCOUNT' => 3,
]
*/
  • toSelectArray
$array = ExampleConstant::toSelectArray();

/*
[
  0 => '登录',
  1 => '注册',
  2 => '找回密码',
  3 => '注销账号',
]
*/

参考

License

MIT

You might also like...
Roach-example-project - Example project to demonstrate how to use RoachPHP in a Laravel project.

Example repository to illustrate how to use roach-php/laravel in a Laravel app. Check app/Spiders/FussballdatenSpider.php for an example spider that c

Magento 2 Megamenu extension is an indispensable component, and plays the role of website navigation to help customers easily categorize and find information
Magento 2 Megamenu extension is an indispensable component, and plays the role of website navigation to help customers easily categorize and find information

Mageno 2 Mega Menu (Magicmenu) helps you create neat and smart navigation menus to display the main categories on your website.

Laravel Podcast Manager is a complete podcast manager package for Laravel 5.3+ that enables you to manage RSS feeds for your favorite podcasts and listen to the episodes in a seamless UI.
Laravel Podcast Manager is a complete podcast manager package for Laravel 5.3+ that enables you to manage RSS feeds for your favorite podcasts and listen to the episodes in a seamless UI.

laravelpodcast | A Laravel podcast manager package - v0.0.8 Introduction Laravel Podcast Manager is a complete podcast manager package for Laravel 5.3

Orangescrum is a simple yet powerful free and open source project management software that helps team to organize their tasks, projects and deliver more.
Orangescrum is a simple yet powerful free and open source project management software that helps team to organize their tasks, projects and deliver more.

Free, open source Project Management software Introduction Orangescrum is the simple yet powerful free and open source project management software tha

OctoberCMS BlogHub Plugin - Extends RainLab's Blog extension with custom meta details, additional archives and more.

BlogHub extends the RainLab.Blog OctoberCMS plugin with many necessary and helpful features such as Moderatable Comments, Promotable Tags, Custom Meta Fields, additional Archives, basic Statistics, Views counter and more.

A simple GitScrum plugin for Wordpress. You will be able to manage your projects without having to leave Wordpress.
A simple GitScrum plugin for Wordpress. You will be able to manage your projects without having to leave Wordpress.

GitScrum Plugin for Wordpress A simple GitScrum plugin for Wordpress. You will be able to manage your projects without having to leave Wordpress. GitS

❄️ Magento 2 Snowflake module allow you to add snow and even more on your site and make winter fun.

❄️ Magento 2 Snowflake module allow you to add snow and even more on your site and make winter fun.

It's basically a dynamic web browser extension that can display notifications with the help of an admin-controlled dynamic API.
It's basically a dynamic web browser extension that can display notifications with the help of an admin-controlled dynamic API.

D-NOTIFIER A self controlled dynamic API based web browser extension built by Sahil Kumar How It Works? It's basically a dynamic web browser extension

The main scope of this extension is to help phpstan to detect the type of object after the Assert\Assertion validation.

PHPStan beberlei/assert extension PHPStan beberlei/assert Description The main scope of this extension is to help phpstan to detect the type of object

Releases(v0.4)
Owner
null
A SilverStripe module for conveniently injecting JSON-LD metadata into the header of each rendered page in SilverStripe

A SilverStripe module for conveniently injecting JSON-LD metadata into the header of each rendered page in Silver

null 4 Apr 20, 2022
salah eddine bendyab 18 Aug 17, 2021
Ratio plugin is a luck plugin. The more lucky you are, the more you win!

Ratio Ratio plugin is a luck plugin. The more lucky you are, the more you win Features When you break a block (Cobblestone), it gives/puts you somethi

Ali Tura Çetin 2 Apr 25, 2022
Magento 2 Blog is an extension that allows you to manage your store and blog

Magento 2 Blog Extension by Magefan Magento 2 Blog is an extension that allows you to manage your store and blog from one place without having to rely

Magefan 243 Dec 21, 2022
UrlFactory help you to manage URL.

UrlFactory UrlFactory is a PHP package for working with URLs. Its offer you to best developer experience to manage and manipulate URLs. UrlFactory off

Nahid Bin Azhar 18 Sep 26, 2022
This is a Native PHP MVC. If you will build your own PHP project in MVC with router, you can clone this ready to use MVC pattern repo.

Welcome to PHP-Native-MVC-Pattern ?? If you will build your own PHP project in MVC with router, you can clone this ready to use MVC pattern repo. Work

null 2 Jun 6, 2022
DiscordLookup | Get more out of Discord with Discord Lookup! Snowflake Decoder, Guild List with Stats, Invite Info and more...

DiscordLookup Get more out of Discord with Discord Lookup! Snowflake Decoder, Guild List with Stats, Invite Info and more... Website Getting Help Tool

Felix 69 Dec 23, 2022