usmanzahid/service-response
Composer 安装命令:
composer require usmanzahid/service-response
包简介
A simple and effective way of communication between different services among your PHP application.
README 文档
README
A minimal and structured way to handle internal service communication in PHP applications.
Instead of returning null, false, throwing exceptions for expected failures, or using loosely structured arrays, ServiceResponse provides a consistent
object containing success status, message, data, and errors. This standardization improves service orchestration, error handling, debugging, and API response
consistency.
The class supports response chaining, allowing higher-level services to preserve and expose root causes from lower-level operations.
Includes
- Core
ServiceResponseclass with fluent, chainable methods - Structured error aggregation
- Previous response chaining for root-cause tracing
- Helper functions for quick response creation
- Consistent structure for success and failure cases
Response Structure
[
'success' => true|false,
'message' => ?string,
'data' => mixed,
'errors' => array,
]
Basic Usage
Success Response
return (new ServiceResponse()) ->withMessage('Payment processed successfully') ->withData(['transaction_id' => $transactionId]);
Failure Response
return (new ServiceResponse()) ->withSuccess(false) ->withMessage('Payment failed') ->withError('card', 'Card declined');
Adding Multiple Errors
return (new ServiceResponse()) ->withSuccess(false) ->withMessage('Validation failed') ->withErrors([ 'email' => ['Email is required'], 'password' => ['Password must be at least 8 characters'], ]);
Chaining Responses Between Services
When one service depends on another, you can attach the previous response to preserve context.
$paymentResponse = $paymentService->charge($order); if ($paymentResponse->wasNotSuccessful()) { return (new ServiceResponse()) ->withSuccess(false) ->withMessage('Order failed') ->withPrevious($paymentResponse); } return (new ServiceResponse()) ->withMessage('Order completed') ->withPrevious($paymentResponse);
Accessing Aggregated Errors
$errors = $response->getAllErrors();
Getting the Root Cause
$root = $response->getRootCause();
Helper Functions
Helper functions provide a concise way to create responses without instantiating the class directly.
Success Helper
return service_response_success( data: ['user_id' => $user->id], message: 'User authenticated' );
Failure Helper
return service_response_fail( errors: ['auth' => ['Invalid credentials']], message: 'Authentication failed' );
From Exception
try { $gateway->charge($card); } catch (Throwable $e) { return service_response_from_exception($e); }
Real-World Examples
Authentication Service
public function authenticate(string $email, string $password): ServiceResponse { $user = $this->repo->findByEmail($email); if (!$user || !$this->hasher->check($password, $user->password)) { return service_response_fail( ['auth' => ['Invalid credentials']], 'Authentication failed' ); } return service_response_success( ['user_id' => $user->id], 'Authenticated successfully' ); }
Payment Service
public function charge(Order $order): ServiceResponse { if ($order->total <= 0) { return service_response_fail( ['amount' => ['Invalid order total']], 'Payment failed' ); } $transactionId = $this->gateway->charge($order); return service_response_success( ['transaction_id' => $transactionId], 'Payment processed' ); }
Orchestrating Multiple Services
$auth = $authService->authenticate($email, $password); if ($auth->wasNotSuccessful()) { return $auth; } $payment = $paymentService->charge($order); if ($payment->wasNotSuccessful()) { return (new ServiceResponse()) ->withSuccess(false) ->withMessage('Checkout failed') ->withPrevious($payment); } return (new ServiceResponse()) ->withMessage('Checkout completed') ->withPrevious($payment);
JSON Serialization
ServiceResponse implements JsonSerializable, allowing it to be safely encoded:
return json_encode($response); // You can also do: $response->jsonSerialize
Frameworks like Laravel will automatically serialize the response:
return response()->json($response);
Exceptionless Flow Control
Use the response status instead of exceptions for expected outcomes.
$response = $paymentService->charge($order); if ($response->wasSuccessful()) { // proceed with fulfillment $fulfillmentService->dispatch($order); } else { // log and return structured failure logger()->warning('Payment failed', $response->toArray()); return $response; }
Notes
- Errors are grouped by key for predictable handling
getAllErrors()merges errors from chained responsestoArray()produces API-ready output- Responses can be safely returned across service boundaries
usmanzahid/service-response 适用场景与选型建议
usmanzahid/service-response 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 05 月 20 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「dto」 「error-handling」 「result-pattern」 「service-response」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 usmanzahid/service-response 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 usmanzahid/service-response 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 usmanzahid/service-response 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Logging and Notifications for Laravel Console Commands.
PHP library for the MUMSYS project
A simple library that allows transform any kind of data to native php data or whatever
Enables simple 404 Page NotFound handling, also for multilingual sites.
Prevent sensitive exception details from leaking in Laravel applications
a package for handle api errors
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 14
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-05-20