monsieurluge / optional
此包已被放弃,不再维护。未建议替代包。
面向可选对象
v1.0.0
2020-03-10 13:33 UTC
Requires (Dev)
- phpmd/phpmd: @stable
- phpstan/phpstan: @stable
- phpunit/phpunit: *
This package is auto-updated.
Last update: 2022-07-10 18:32:59 UTC
README
Optional 库的目标是优雅地处理可选参数,以避免使用如 if
或 switch
等控制结构,以及避免使用多种返回类型。
代码也变得更加声明式。
示例
将用户数据发送到模板
上下文:我们想要显示用户数据,但电话号码是可选的。
通常所见
<?php // ---------------------------------------- interfaces interface PhoneNumber { public function toString(): string; } interface User { public function firstname(): string; public function lastname(): string; public function phone(): PhoneNumber|null; } // ---------------------------------------- implementation $this->templateEngine->render( 'template/file/path/', [ 'firstname' => $user->firstname(), 'lastname' => $user->lastname(), 'phone' => is_null($user->phone()) ? '--.--.--.--.--' : $user->phone()->toString(), ] );
使用 Optional
<?php // ---------------------------------------- interfaces interface PhoneNumber { public function toString(): string; } interface User { public function firstname(): string; public function lastname(): string; public function phone(): Maybe; // Maybe<PhoneNumber> } // ---------------------------------------- implementation $this->templateEngine->render( 'template/file/path/', [ 'firstname' => $user->firstname(), 'lastname' => $user->lastname(), 'phone' => $user->phone() ->map(function (PhoneNumber $phone) { return $phone->toString(); }) ->getOr('--.--.--.--.--'), ] );