PHP 的选项类型
该包为 PHP 实现了 Option 类型!
Option 类型适用于以下场景:有时你可能返回一个值(通常是对象),而有时则可能根据参数或其他运行时因素返回一个基础值(通常是 null)。
很多时候,你会忘记处理应该返回基础值的情况。当然,这并非有意为之,但也许你并未考虑到系统的所有可能状态;又或者你确实覆盖了所有情况,但随着时间的推移,代码被重构,其中一些检查可能变得无效或不完整。突然之间,在不知不觉中,基础值的情况就不再被处理了。结果,你有时可能会遇到致命的 PHP 错误,提示你在非对象上调用了方法;用户可能会看到空白页面,甚至更糟的情况。
一方面,Option 类型迫使开发者有意识地同时考虑两种情况。 情况(返回一个值,或返回一个基础值)。这本身就会 已经让你的代码更健壮了。另一方面,Option 类型也 允许API开发者提供更简洁的API方法,并赋予其 API用户如何消费这些方法。
Installation is super-easy via Composer:
$ composer require phpoption/phpoption或者手动将其添加到你的 composer.json 文件中。
class MyRepository
{
public function findSomeEntity($criteria): \PhpOption\Option
{
if (null !== $entity = $this->em->find(...)) {
return new \PhpOption\Some($entity);
}
// We use a singleton, for the None case.
return \PhpOption\None::create();
}
}如果你正在使用现有的库,也可以使用更简短的版本。
默认情况下,它将 null 视为 None,而将其他所有内容视为 Some 的情况:
class MyRepository
I am a professional English-to-Simplified Chinese translator. Translate the user's text into fluent, natural Simplified Chinese. Preserve Markdown structure (headings, lists, links, emphasis) exactly. Do NOT translate URLs, code identifiers, package names, or brand names; keep them as-is. Output ONLY the translated text, with no explanation, no preamble, and no quotation marks.
public function findSomeEntity($criteria): \PhpOption\Option
Please provide the text you would like me to translate into Simplified Chinese.暂无开放 Issues,或尚未同步最近议题。