一些尼亚托克 / 结果类型
类似函数的通用结果类型:成功或错误
1.4.0
2023-06-20 08:45 UTC
Requires
- php: 7.4.* || 8.0.* || 8.1.* || 8.2.*
Requires (Dev)
- phpunit/phpunit: ^9.5
- psalm/plugin-phpunit: ^0.17
- squizlabs/php_codesniffer: ^3.6
- vimeo/psalm: ^4.7
This package is auto-updated.
Last update: 2024-09-20 13:54:25 UTC
README
一个代表具有成功和错误状态的通用结果类型的库,旨在帮助在PHP中实现函数式编程模式。
它使用 Psalm 注释进行泛型类型化,因此如果您想进行代码的类型检查,建议您使用 Psalm。
为什么使用这个库,如果已经有了 graham-campbell/result-type
呢?
遗憾的是,这个库有几个缺点
- 尽管它也使用 Psalm 注释进行类型化,但实际上使用和检查它们可能会很痛苦。
- 它与
phpoption/phpoption
库耦合,而这个库不幸也存在同样的问题。 - 结果接口中没有便利的方法可以从中获取任意值。
最好与 someniatko/result-type-psalm-plugin
一起使用!
安装
此库需要 PHP 7.4、8.0、8.1 或 8.2。您可以通过 Composer 安装它。
composer install someniatko/result-type
使用方法
有关详细信息,请参阅 ResultInterface
。
示例
<?php use Someniatko\ResultType\Success; use Someniatko\ResultType\Error; $value = (new Success('Let it be')) ->map(fn (string $s) => substr_count($s, ' ')) // Success<2> ->chain(fn (int $wordsCount) => $wordsCount > 3 ? new Success('Long text') : new Error('short text') ) // Error<'short text'> ->map(fn (string $s) => str_replace(' ', '', $s)) // will not be called because we're in Error result ->mapError(fn (string $s) => strtoupper($s)) // Error<'SHORT TEXT'> ->get(); // 'SHORT TEXT'