JSend 规范的简单 PHP 实现。

v6.0.0 2023-12-15 13:04 UTC

This package is auto-updated.

Last update: 2024-09-21 10:27:26 UTC


README

Build Status Build Status Build Status Build Status

Code Climate
Issue Count

Total Downloads

JSend

JSend 规范的简单 PHP 实现。

使用方法

use JSend\JSendResponse;

新建响应

$success = new JSendResponse('success', $data);
$fail = new JSendResponse('fail', $data);
$error = new JSendResponse('error', $data, 'Not cool.', 9001);
$success = JSendResponse::success($data);
$fail = JSendResponse::fail($data);
$error = JSendResponse::error('Not cool.', 9001, $data);

注意:如果状态无效或创建错误时没有消息,将抛出 InvalidJSendException

将 JSendResponse 转换为 JSON

重写 __toString() 以自动编码 JSON。

$json = $success->encode();
$json = (string) $success;

由于 JSendResponse 实现 JsonSerializable,您可以直接在 json_encode 中使用该对象。

json_encode($success);

设置标志

如有需要,您可以设置标志。

$success->setEncodingOptions(\JSON_PRETTY_PRINT | \JSON_BIGINT_AS_STRING);
$json = $success->encode();

将 JSON 转换为 JSendResponse

try {
    $response = JSendResponse::decode($json);
} catch (InvalidJSendException $e) {
    echo "You done gone passed me invalid JSend.";
}

发送 JSON 作为 HTTP 响应

这会将 Content-Type 标头设置为 application/json 并输出 JSON。

$jsend = new JSendResponse('success', $data);
$jsend->respond();

获取信息

$isSuccess = $response->isSuccess();
$isError = $response->isError();
$isFail = $response->isFail();
$status = $response->getStatus();
$data = $response->getData();
$array = $response->asArray();

此外,您还可以在错误上调用以下方法。如果状态不是 error,则抛出 BadMethodCallException,因此请先进行检查。

if ($response->isError()) {
    $code = $response->getErrorCode;
    $message = $response->getErrorMessage;
}

开发

为了您的方便,提供了一个带有正确依赖项(PHP、Composer)的 dockerfile。请使用这些依赖项来运行各种事物(Composer、PHPUnit 等)。您需要安装 docker,但不需要 PHPComposer 或其他依赖项。

设置和本地环境使用

要开始使用本地环境进行测试和调试,您只需在项目检出根目录中打开一个 shell。然后运行以下命令。

make build install

该命令应偶尔运行以保持本地环境更新。例如,当 Composer 依赖项更改时。

使用 shell

要打开 docker 容器中的 shell,请运行以下命令。

make shell

可用命令位于 /bin 中。

本地运行代码质量工具

我们使用各种工具来保持库的代码质量。要运行其中一个工具,只需运行

make <tool_name>

可用工具

  • phpstan PHPStan 是一种静态分析工具,可以检测各种代码问题。
  • phpunit PHPUnit 是我们用于此库的单元测试框架。
  • codeclimate CodeClimate

注意

  • 请注意,composer.lock 文件被忽略。

致谢

此库由 Jamie Schembri 编写。它于 2015 年 12 月转移到当前账户 Nanne Huiges