huangdijia/constants

A constants component for PHP.

v1.0.0 2023-08-06 04:34 UTC

This package is auto-updated.

Last update: 2024-07-06 06:26:53 UTC


README

PHP Constants

Latest Test Latest Stable Version Total Downloads GitHub license

A constants component for PHP.

Installation

composer require huangdijia/constants

Usage

  • Before
class ErrorCode
{
    const NOT_FOUND = 404;
    const SERVER_ERROR = 500;

    public static $errors = [
        self::NOT_FOUND => 'Not Found',
        self::SERVER_ERROR => 'Server Error',
    ];

    public static function getMessage($code)
    {
        return self::$errors[$code] ?? '';
    }
}
  • Now
namespace App\Constants;

use Huangdijia\Constants\AbstractConstants;

/**
 * @method static string getMessage(string $code)
 * @method static string getMessageCn(string $code)
 * @method static string getMessageEn(string $code)
 */
class ErrorCode extends AbstractConstants
{
    /**
     * @Message("%s not found!")
     */
    const NOT_FOUND = 404;

    /**
     * @Message("Server Error")
     */
    const SERVER_ERROR = 500;

    /**
     * @MessageCn("成功")
     * @MessageEn("Success")
     */
    const OK = 1;

    /**
     * @MessageCn("失败")
     * @MessageEn("Failure")
     */
    const FAILURE = 0;
}

var_dump(ErrorCode::getMessage(ErrorCode::SERVER_ERROR)); // Server Error
var_dump(ErrorCode::getMessage(ErrorCode::NOT_FOUND, '/api')); // /api not found!
var_dump(ErrorCode::getMessageCn(ErrorCode::OK)); // 成功
var_dump(ErrorCode::getMessageEn(ErrorCode::OK)); // Success