prewk/result

Result object for PHP inspired by Rust

Maintainers

👁 prewk

Package info

github.com/prewk/result

pkg:composer/prewk/result

Statistics

Installs: 948 553

Dependents: 9

Suggesters: 0

Stars: 121

Open Issues: 9

4.1.0 2025-08-19 18:47 UTC

Requires

Suggests

None

Provides

None

Conflicts

None

Replaces

None

(MIT or Apache-2.0) aac58a55dd66e99fb34345873f870dc8bfa07a54

  • Oskar Thornblad <oskar.thornblad.woop@gmail.com>

README

A PHP implementation of Rust's Result type with roughly the same API.

Version information

Version 4.x.x requires PHP 8.1.0+. Make sure you match the versions for this and the Option library if you use both.

Installation

composer require prewk/result

Overview

use Prewk\Result;
use Prewk\Result\{Ok, Err};

function someApiCall(): Result {
 // ...
 if ($apiCallSuccesful) {
 return new Ok($results);
 } else {
 return new Err($error);
 }
}

function anotherApiCall(): Result {
 // ...
 if ($apiCallSuccesful) {
 return new Ok($results);
 } else {
 return new Err($error);
 }
}

// Fallback to value
$value = someApiCall()->unwrapOr(null);

// Fallback to result and throw an exception if both fail
$value = someApiCall()->orElse(function($err) {
	return anotherApiCall();
})->unwrap();

// Throw custom exception on error
$value = someApiCall()->expect(new Exception("Oh noes!"));

Helpers

Optional global helper functions exist to simplify result object construction:

ok(); // new Prewk\Result\Ok(null);
ok($val); // new Prewk\Result\Ok($val);
err($e); // new Prewk\Result\Err($e);

Add the following to your composer.json:

{
 "autoload": {
 "files": ["vendor/prewk/result/helpers.php"]
 }
}

API deviations from Rust

Exceptions

If an Err containing an Exception is unwrapped, that Exception will be thrown. Otherwise a generic ResultException will be thrown.

Gotchas

Note that or and and will be evaluated immediately:

// This will call all three api calls regardless of successes/errors
$this
	->apiCall()
	->or(anotherApiCall())
	->and(thirdApiCall());

See andThen and orElse for lazy evaluation.

License

MIT & Apache 2.0