sassnowski/option

Scala中Option数据类型的PHP基本实现。

0.2.0 2016-05-04 21:29 UTC

This package is auto-updated.

Last update: 2024-08-29 04:48:39 UTC


README

Build Status Coverage Status Code Climate SensioLabsInsight

Scala中Option数据类型的PHP实现(或者如果你希望,Haskell中的Maybe)。

免责声明:此包不打算用于生产环境。它的目的是作为一个编码练习,让我了解如何实现PHP中的Option类型。如果你想在生产环境中使用,我建议你使用https://github.com/schmittjoh/php-option

安装

通过composer安装此包

$ composer require sassnowski/option

这就完成了!现在你可以在代码中使用它了。

function divide($a, $b)
{
	if (0 === $b)
	{
		return Option::None();
	}
	
	return new Option($a / $b);
}

$result = divide(10, 5);
$result->get(); // 2

$result2 = divide(10, 0);
$result->isDefined(); // false

摘要

Option表示一个可选值,换句话说,一个可能不存在的值。有时它被描述为最多包含一个元素的列表。

Option用于那些通常可能会使用null的地方,例如数据库查询的结果。更普遍的说法是:如果一个计算对于某些输入未定义,它可能会返回一个Option

Option::map($func)

使用Option意味着大量代码需要了解这种数据类型。为了仍然能够重用操作未封装值的函数,此类提供了一个map函数。

map函数的目的是将通常在常规值上操作的函数提升到现在可以在Option值上操作。形式上,它将类型

a -> b

的函数转换为类型

Option a -> Option b

示例

// Note: This example uses PHP 7 type hinting. This is in no 
// way necessary for this package to work and is simply there 
// to illustrate the types that these functions are supposed to
// operate on.

function length(string $a): int
{
	return strlen($a);
}

$length1 = (new Option("abc"))->map('length');
$length1->isDefined(); // true
$length1->get(); // 3

// The length function never gets executed, since we're 
// dealing with an undefined value.
$length2 = Option::None->map('length');
$length2->isDefined(); // false
$length2->get(); // RuntimeException

上述示例将类型为string -> int的函数length提升为类型为Option string -> Option int的函数。这意味着我们仍然可以编写和重用那些没有考虑可选值的函数,并简单地将它们提升为可以处理Option的函数。

map方法的一个重要特点是,如果我们处理的是未定义的值,那么被映射到Option上的函数永远不会被执行。

Option::flatMap($func)

待办事项

Option::getOrElse($default)

待办事项

Option::orElse($alternative)

待办事项

Option::isDefined()

此函数简单地返回true,如果值不是null,否则返回false

许可证

MIT