atournayre / null
提供空对象
dev-main
2024-06-13 07:48 UTC
Requires
- php: >=8.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.1
- phpstan/phpstan: ^1
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2024-09-13 08:20:35 UTC
README
此包提供了一种处理应用中可空值的方法。
入门
安装
$ composer require atournayre/null
使用
标题来自 Tests 命名空间中的 Fixture。
标准情况
以前你有一个返回类型 string,现在你可以使用 Title 对象。
$title = Title::create('My title'); $title->title; // 'My title' $title->isNull(); // false $title->isNotNull(); // true
可空情况
以前你有一个返回类型 null,现在你可以使用 Title 对象。
$title = Title::asNull(); $title->title; // 'Empty title' $title->isNull(); // true $title->isNotNull(); // false
可能可空情况
以前你有一个返回类型 ?string,现在你可以使用 Title 对象。
如果你不确定值是否为 null,你可以使用 orNull() 方法,它是 ?-> 运算符的替代。
$title = Title::create('My title') ->orNull() ->title; // 'My title'
$title = Title::asNull() ->orNull() ->title; // 'Empty title'
除了使用 orNull() 方法外,你还可以使用 orThrow() 方法来抛出一个异常,如果值为 null。
$title = Title::asNull() ->orThrow(new \RuntimeException('Title is null'));
orThrow() 还接受一个可调用来抛出一个带有自定义消息的异常。
$title = Title::asNull() ->orThrow(fn () => new \RuntimeException('Title is null'));
贡献
请阅读 CONTRIBUTING.md 了解我们的行为准则以及向我们提交拉取请求的过程。
在编写你的修复/功能后,你可以运行以下命令以确保一切正常。
# Install dev dependencies $ composer install # Running tests and quality tools locally $ make all