typedphp/optional

一个用于减少null检查所需代码的库。

0.2.1 2014-11-02 17:15 UTC

This package is auto-updated.

Last update: 2024-09-19 01:01:34 UTC


README

Build Status Code Quality Code Coverage Version License

此库受Johannes Schmitt的代码(链接)和Igor Wiedler的写作(链接)的启发,旨在减少null检查所需的代码。它是TypedPHP的一部分(链接)。

示例

<?php

require("vendor/autoload.php");

use TypedPHP\Optional\Optional;

class Foo
{
    public function hello()
    {
        return new Bar();
    }
}

class Bar
{
    public function world()
    {
        return "hello world";
    }
}

$optional = new Optional(new Foo());
$optional->hello()->world()->value(); // "hello world"
<?php

require("vendor/autoload.php");

use TypedPHP\Optional\None;

$none = new None();
$none->hello()->world()->value(); // null
<?php

require("vendor/autoload.php");

use TypedPHP\Optional\None;

$none = new None();
$none
    ->none(function() { print "none"; }); // "none" printed
    ->value(function($value) { print $value; }); // $value not printed

use TypedPHP\Optional\Optional;

$optional = new Optional("hello world");
$optional
    ->none(function() { print "none"; }); // "none" not printed
    ->value(function($value) { print $value; }); // "hello world" printed

一旦一个Optional方法调用返回一个空值,它将被转换为None

安装

❯ composer require "typedphp/optional:*"

测试

❯ composer create-project "typedphp/optional:*" .
❯ vendor/bin/phpunit