jefvda/php-result-monad

PHP的'Result'单子类型

1.0.2 2023-12-01 22:00 UTC

This package is auto-updated.

Last update: 2024-09-30 01:51:33 UTC


README

概述

PHP Result Monad 库提供了一种简单而有效的方式来处理操作的结果,提供了一个无需抛出异常的替代异常处理方法。该库的核心组件是Result类,它封装了操作的输出,可以从成功值或异常中创建。

🔗 安装

您可以通过Composer安装此包

composer require jefvda/php-result-monad

Result 类

工厂方法

createFromValue

/**
 * @param mixed $value The value associated with the result.
 * @return Result The successful Result which includes the value.
 */
public static function createFromValue(mixed $value): self

-> 使用提供的值创建一个成功的Result实例。

createFromException

/**
 * @param Exception $exception The exception that explains why the result was not successful.
 * @return Result The not successful Result that includes the exception.
 */
public static function createFromException(Exception $exception): self

-> 使用提供的异常创建一个不成功的Result实例。

公共方法

获取器

  • getValue -> 返回与结果关联的值。
  • getException -> 返回与结果关联的异常。
  • isSuccess -> 返回一个布尔值,指示操作是否成功。

match

/**
 * @param callable $valueCallback The callback for successful results.
 * @param callable $exceptionCallback The callback for unsuccessful results.
 * @return mixed The return value of the callback that has been called.
 */
public function match(callable $valueCallback, callable $exceptionCallback): mixed

-> 允许根据结果进行匹配,根据成功或失败执行适当的回调。

用法

以下是一个演示Result类基本用法的简要示例

// Create a successful result with a value
$successResult = Result::createFromValue('Hello, Result!');

// Create an unsuccessful result with an exception
$exception = new \Exception('Something went wrong.');
$failureResult = Result::createFromException($exception);

// Match on the results
$successMessage = $successResult->match(
    fn ($value) => 'Success: ' . $value,
    fn ($exception) => 'Failure: ' . $exception,
);

$failureMessage = $failureResult->match(
    fn ($value) => 'Success: ' . $value,
    fn ($exception) => 'Failure: ' . $exception,
);

echo $successMessage; // Will display 'Success: Hello, Result!' -> as the `Result` was successful
echo $failureMessage; // Will display 'Failure: Something went wrong.' -> as the `Result` was not successful