prewk / result
受Rust启发的PHP结果对象
4.0.0
2024-05-10 18:17 UTC
Requires
- php: >=8.1.0
- prewk/option: >= 1.3.0
Requires (Dev)
- ergebnis/composer-normalize: 2.42.0
- infection/infection: 0.27.11
- phpunit/phpunit: 10.5.15
- psalm/plugin-phpunit: 0.19.0
- symplify/easy-coding-standard: 12.1.14
- vimeo/psalm: 5.24.0
- dev-master
- 4.0.0
- 3.3.0
- 3.2.0
- 3.1.1
- 3.1.0
- 3.0.0
- 2.1.1
- 2.1.0
- 2.0.0
- 1.2.0
- 1.1.0
- 1.0.2
- 1.0.1
- 1.0.0
- 0.0.5
- 0.0.4
- 0.0.3
- 0.0.2
- 0.0.1
- dev-dependabot/composer/symplify/easy-coding-standard-12.3.4
- dev-dependabot/github_actions/shivammathur/setup-php-2.31.1
- dev-dependabot/composer/phpunit/phpunit-10.5.26
- dev-dependabot/composer/vimeo/psalm-5.25.0
- dev-dependabot/composer/ergebnis/composer-normalize-2.43.0
- dev-dependabot/github_actions/actions/checkout-4.1.7
- dev-dependabot/github_actions/coverallsapp/github-action-2.3.0
- dev-dependabot/composer/guzzlehttp/psr7-2.5.0
- dev-dependabot/composer/guzzlehttp/guzzle-7.4.5
This package is auto-updated.
Last update: 2024-09-01 09:07:12 UTC
README
这是一个PHP实现,模仿了Rust的Result类型,API基本相同。
版本信息
版本4.x.x需要PHP 8.1.0及以上。如果您同时使用此库和Option库,请确保版本匹配。
安装
composer require prewk/result
概述
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!"));
辅助函数
存在可选的全局辅助函数,用于简化结果对象的构建。
ok(); // new Prewk\Result\Ok(null); ok($val); // new Prewk\Result\Ok($val); err($e); // new Prewk\Result\Err($e);
将以下内容添加到您的 composer.json
文件中:
{ "autoload": { "files": ["vendor/prewk/result/helpers.php"] } }
Rust API差异
异常
如果解包包含 Exception
的 Err
,则抛出该异常。否则,将抛出通用的 ResultException
。
注意事项
注意,or
和 and
将立即进行评估。
// This will call all three api calls regardless of successes/errors $this ->apiCall() ->or(anotherApiCall()) ->and(thirdApiCall());
请参阅 andThen
和 orElse
以实现延迟评估。
许可证
MIT & Apache 2.0