PHPackages                             arielespinoza07/result-pattern - 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. arielespinoza07/result-pattern

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

arielespinoza07/result-pattern
==============================

A modern implementation of the Result pattern for handling operation outcomes in PHP 8.3+

v2.2.0(2mo ago)171MITPHPPHP ^8.3CI passing

Since Jun 9Pushed 2mo agoCompare

[ Source](https://github.com/ArielEspinoza07/result-pattern)[ Packagist](https://packagist.org/packages/arielespinoza07/result-pattern)[ RSS](/packages/arielespinoza07-result-pattern/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (4)Versions (8)Used By (0)

Result Pattern
==============

[](#result-pattern)

 [ ![Build Status](https://github.com/ArielEspinoza07/result-pattern/actions/workflows/tests.yml/badge.svg) ](https://github.com/ArielEspinoza07/result-pattern/actions) [ ![Total Downloads](https://camo.githubusercontent.com/a1896dce1ecd2526e8a18f872979c2423a2dada82d1005db0dc017d89a5cdb2e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f617269656c657370696e6f7a6130372f726573756c742d7061747465726e2e7376673f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/arielespinoza07/result-pattern) [ ![Latest Stable Version](https://camo.githubusercontent.com/15015e445b6e580673be045eeaa82789f192f000fa565f83b2368c08dfa7075d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f617269656c657370696e6f7a6130372f726573756c742d7061747465726e2e7376673f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/arielespinoza07/result-pattern) [ ![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667) ](https://github.com/ArielEspinoza07/result-pattern/blob/main/LICENSE)

---

A modern, immutable implementation of the Result pattern for PHP 8.3+.

> **Requires [PHP 8.3+](https://php.net/releases/)**

---

Features
--------

[](#features)

- Type-safe result handling with strict type hints and PHPStan level max
- Immutable objects using PHP 8.3+ `readonly` classes
- Fluent, chainable API: `map → flatMap → recover → fold`
- Full generic type inference via `@template` annotations
- Comprehensive test suite with Pest PHP and type coverage

---

Project Structure
-----------------

[](#project-structure)

```
src/
├── Failure.php
├── Success.php
└── Result.php

```

---

Installation
------------

[](#installation)

```
composer require arielespinoza07/result-pattern
```

---

Quick Start
-----------

[](#quick-start)

```
use ArielEspinoza07\ResultPattern\Result;

// Create results
$ok  = Result::success(42);
$err = Result::failure('something went wrong');

// Wrap a throwing operation
$result = Result::attempt(fn () => riskyOperation());

// Convert nullable to Result
$result = Result::fromNullable($user, new UserNotFoundException());

// Transform and compose
$value = Result::success(2)
    ->map(fn ($x) => $x * 10)
    ->flatMap(fn ($x) => Result::success($x + 5))
    ->getValueOr(0); // 25

// Handle both branches
$output = $result->fold(
    onSuccess: fn ($v) => "Got: {$v}",
    onFailure: fn ($e) => "Error: {$e}",
);
```

---

API Reference
-------------

[](#api-reference)

### Static constructors

[](#static-constructors)

MethodDescription`Result::success($value)`Wraps a value in a `Success``Result::failure($error)`Wraps an error in a `Failure``Result::attempt(callable, array $only = [])`Executes a callable; catches `Throwable` as `Failure`. Pass `$only` to catch only specific exception types.`Result::fromNullable($value, $error)``null` → `Failure($error)`, non-null → `Success($value)``Result::zip(Result ...$results)`All succeed → `Success([values])`, first failure wins (fail-fast)`Result::collect(array $results)`Processes all results; returns `Failure([errors])` with every error collected (fail-all)### Instance methods

[](#instance-methods)

MethodDescription`isSuccess()``true` if `Success``isFailure()``true` if `Failure``getValue()`Returns value (throws on `Failure`) — prefer `getValueOr()``getError()`Returns error (throws on `Success`) — prefer `getErrorOr()``getValueOr($default)`Safe value access with fallback`getErrorOr($default)`Safe error access with fallback`toNullable()``Success($v)` → `$v`, `Failure` → `null``map(callable)`Transform the value; no-op on `Failure``mapError(callable)`Transform the error; no-op on `Success``flatMap(callable)`Chain a `Result`-returning callable on `Success``flatMapError(callable)`Chain a `Result`-returning callable on `Failure``recover(callable)`Convert `Failure` → `Success` via fallback value`recoverWith(callable)`Convert `Failure` → `Result` (recovery can itself fail)`tap(callable)`Run a side-effect on `Success` without modifying the result`onSuccess(callable)`Run a side-effect on `Success``onFailure(callable)`Run a side-effect on `Failure``fold(onSuccess, onFailure)`Collapse both branches into a single value---

Documentation
-------------

[](#documentation)

- [Basic Success and Failure Examples](docs/basic-examples.md)
- [attempt() / try() Method Examples](docs/try-method-examples.md)
- [zip() and collect() Examples](docs/zip-collect-examples.md)
- [fromNullable() Examples](docs/from-nullable-examples.md)
- [onSuccess and onFailure Examples](docs/on-success-failure-examples.md)
- [tap() and toNullable() Examples](docs/tap-to-nullable-examples.md)
- [Map Method Examples](docs/map-method-examples.md)
- [mapError() and flatMapError() Examples](docs/map-error-examples.md)
- [FlatMap Method Examples](docs/flat-map-method-examples.md)
- [Fold Method Examples](docs/fold-method-examples.md)
- [recover() and recoverWith() Examples](docs/recover-examples.md)
- [Error Handling Examples](docs/error-handling-examples.md)

---

Development
-----------

[](#development)

### Requirements

[](#requirements)

- PHP 8.3+
- Composer 2.0+

### Setup

[](#setup)

```
git clone https://github.com/ArielEspinoza07/result-pattern.git
cd result-pattern
composer install
```

### Quality Tools

[](#quality-tools)

```
composer check       # lint + analyse + test (all-in-one)
composer lint        # check code style (Pint)
composer lint:fix    # fix code style
composer analyse     # static analysis (PHPStan level max)
composer test        # run tests (Pest PHP)
composer test:coverage # run tests with coverage report
```

---

Contributing
------------

[](#contributing)

See [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions, code conventions, and PR guidelines.

---

License
-------

[](#license)

[MIT License](LICENSE)

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance86

Actively maintained with recent releases

Popularity13

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity56

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 ~53 days

Recently: every ~67 days

Total

6

Last Release

67d ago

Major Versions

v1.0.2 → v2.0.02025-06-10

### Community

Maintainers

![](https://www.gravatar.com/avatar/eb7e924ed76cec332097558625b18c8591b7ee627ff2efd07c07486844c63437?d=identicon)[ArielEspinoza07](/maintainers/ArielEspinoza07)

---

Top Contributors

[![ArielEspinoza07](https://avatars.githubusercontent.com/u/9816498?v=4)](https://github.com/ArielEspinoza07 "ArielEspinoza07 (124 commits)")

---

Tags

phpresult-patternphpOutcomeresult-pattern

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/arielespinoza07-result-pattern/health.svg)

```
[![Health](https://phpackages.com/badges/arielespinoza07-result-pattern/health.svg)](https://phpackages.com/packages/arielespinoza07-result-pattern)
```

###  Alternatives

[imanghafoori/laravel-anypass

A minimal yet powerful package to help you in development.

21421.6k](/packages/imanghafoori-laravel-anypass)

PHPackages © 2026

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