PHPackages                             usmanzahid/service-response - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. usmanzahid/service-response

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

usmanzahid/service-response
===========================

A simple and effective way of communication between different services among your PHP application.

v1.1.0(2mo ago)01MITPHPPHP ^8.1

Since May 20Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/usmanx03/service-response)[ Packagist](https://packagist.org/packages/usmanzahid/service-response)[ RSS](/packages/usmanzahid-service-response/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (3)Used By (0)

Service Response
================

[](#service-response)

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
--------

[](#includes)

- Core `ServiceResponse` class 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
------------------

[](#response-structure)

```
[
    'success' => true|false,
    'message' => ?string,
    'data' => mixed,
    'errors' => array,
]
```

---

Basic Usage
-----------

[](#basic-usage)

### Success Response

[](#success-response)

```
return (new ServiceResponse())
    ->withMessage('Payment processed successfully')
    ->withData(['transaction_id' => $transactionId]);
```

### Failure Response

[](#failure-response)

```
return (new ServiceResponse())
    ->withSuccess(false)
    ->withMessage('Payment failed')
    ->withError('card', 'Card declined');
```

---

Adding Multiple Errors
----------------------

[](#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
-----------------------------------

[](#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

[](#accessing-aggregated-errors)

```
$errors = $response->getAllErrors();
```

### Getting the Root Cause

[](#getting-the-root-cause)

```
$root = $response->getRootCause();
```

---

Helper Functions
----------------

[](#helper-functions)

Helper functions provide a concise way to create responses without instantiating the class directly.

### Success Helper

[](#success-helper)

```
return service_response_success(
    data: ['user_id' => $user->id],
    message: 'User authenticated'
);
```

### Failure Helper

[](#failure-helper)

```
return service_response_fail(
    errors: ['auth' => ['Invalid credentials']],
    message: 'Authentication failed'
);
```

### From Exception

[](#from-exception)

```
try {
    $gateway->charge($card);
} catch (Throwable $e) {
    return service_response_from_exception($e);
}
```

---

Real-World Examples
-------------------

[](#real-world-examples)

### Authentication Service

[](#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

[](#payment-service)

```
public function charge(Order $order): ServiceResponse
{
    if ($order->total  ['Invalid order total']],
            'Payment failed'
        );
    }

    $transactionId = $this->gateway->charge($order);

    return service_response_success(
        ['transaction_id' => $transactionId],
        'Payment processed'
    );
}
```

---

### Orchestrating Multiple Services

[](#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
------------------

[](#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
--------------------------

[](#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
-----

[](#notes)

- Errors are grouped by key for predictable handling
- `getAllErrors()` merges errors from chained responses
- `toArray()` produces API-ready output
- Responses can be safely returned across service boundaries

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance86

Actively maintained with recent releases

Popularity1

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~285 days

Total

2

Last Release

71d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3e7f93f7407d7c7fbe8a27d3c8aaf863066168fbb6e1e75b0b847511571a4236?d=identicon)[Usmanzahidcode](/maintainers/Usmanzahidcode)

---

Top Contributors

[![usmanx03](https://avatars.githubusercontent.com/u/112874031?v=4)](https://github.com/usmanx03 "usmanx03 (9 commits)")

---

Tags

phpdtoerror handlingresult-patternservice-response

### Embed Badge

![Health badge](/badges/usmanzahid-service-response/health.svg)

```
[![Health](https://phpackages.com/badges/usmanzahid-service-response/health.svg)](https://phpackages.com/packages/usmanzahid-service-response)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
