petrknap/optional 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

petrknap/optional

最新稳定版本:v3.5.0

Composer 安装命令:

composer require petrknap/optional

包简介

Optional (like in Java Platform SE 8 but in PHP)

README 文档

README

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).

This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.

-- Optional (Java Platform SE 8)

It is an easy way to make sure that everyone has to check if they have (not) received a null.

Examples

namespace PetrKnap\Optional;

/** @var Optional<string> $optionalString */
$optionalString = Optional::of('data');
if ($optionalString->isPresent()) {
    echo $optionalString->get();
}

OptionalResource::ofFalsable(tmpfile())->ifPresent(function ($tmpFile): void {
    fwrite($tmpFile, 'data');
    fclose($tmpFile);
}, else: fn () => print('tmpfile() failed'));

Create and use your own typed optional

namespace PetrKnap\Optional;

/**
 * @extends OptionalObject<Some\DataObject>
 */
class YourOptional extends OptionalObject {
    protected static function getInstanceOf(): string {
        return Some\DataObject::class;
    }
}
TypedOptional::register(YourOptional::class); // optional recommended step

function your_strong_typed_function(YourOptional $input): YourOptional {
    return YourOptional::empty();
}

/**
 * @param Optional<Some\DataObject> $input
 *
 * @return Optional<Some\DataObject>
 */
function your_weak_typed_function(Optional $input): Optional {
    return YourOptional::empty();
}

Run composer require petrknap/optional to install it. You can support this project via donation. The project is licensed under the terms of the LGPL-3.0-or-later.

统计信息

  • 总下载量: 65.99k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 1
  • 依赖项目数: 6
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: LGPL-3.0-or-later
  • 更新时间: 2024-05-10