sylvrs / libresult
一个库,用于添加来自其他流行编程语言的Result monad
这个包的官方仓库似乎已丢失,因此该包已被冻结。
0.1.1
2022-07-16 18:04 UTC
Requires
- php: >=8.0
Requires (Dev)
- phpstan/phpstan: >=1.8.1
- phpunit/phpunit: >=9.5
This package is auto-updated.
Last update: 2024-05-16 22:11:23 UTC
README
这个库是PHP实现的Result monad,存在于许多流行的编程语言中,包括Haskell、Elm、Kotlin和Rust。
安装
要使用Composer安装此库,请运行以下命令:composer require sylvrs/libresult
用法
库的用法与其他语言的monads类似。
创建结果
结果的基本创建如下
/** * @return Result<string, string> */ function create_result(): Result { return mt_rand(0, 1) > 0 ? new Ok("success!") : new Err("error!"); } $result = create_result();
值提取
从那里,有几种方法可以从结果中获取值
// Using PHP's match expression $value = match (true) { $result instanceof Ok => $result->getValue(), $result instanceof Err => $result->getError(), // This will never occur, but is required for PHPStan to be happy in most levels default => assert(true) }; // Using `Result->get()` // Note: This will return null if the result is an error $value = $result->get(); // Using `Result->unwrap()` // Note: This will throw an exception if the result is an error $value = $result->unwrap();
有用方法
此外,还有其他可能对处理结果有用的方法
// Using `Result->asArray()` // If the result is Ok, the array shape is [TValue, null]. Otherwise, the array shape is [null, TError] [$value, $error] = $result->asArray(); // Using `Result->getOr()` $value = $result->getOr("default value");
错误处理
对于已知结果是错误的情况,您可以使用Result->unwrapError()
// Note: If the result is *not* an error, this will throw an exception $error = $result->unwrapError();
问题/功能请求
任何问题或请求应在此处报告这里。