huangdijia / constants
A constants component for PHP.
v1.0.0
2023-08-06 04:34 UTC
Requires
- php: >=7.1
Requires (Dev)
- huangdijia/php-coding-standard: ^1.2
- phpstan/phpstan: ^1.0
- phpunit/phpunit: >=7.0
README
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