第一次分享东西
项目地址: https://github.com/lisqorz/option
除了这些,其实还想在里面加上 PHP 的 标准库方法,这样就可以更加函数式了
小例子
case 1
// Option
$res = Some($db->get())->expect(new \Exception("msg"));
// native
$res = $db->get();
if (is_null($res)) {
throw new \Exception("msg");
}
case2
// Option
$_POST["hello"] = null;
Some($_POST['hello'])->unwrapOr("hi"); // hi
$_POST["hello"] = "hello";
Some($_POST['hello'])->unwrapOr("hi"); // hello
// ... but we have $_POST["hello"]??"hi" 2333
Case3
// scenario
$obj = new Obj();
$obj->attr = null; // attr is Object;
// Option
// None
$attr = Some($obj->attr)->andThen(function($attr){
return "";
})->unwrapOr("no success");
//Some
$attr = Some(1)->andThen(function($attr){
return null;
})->unwrapOr("no success");
// native
$attr = "no success";
if ($obj->attr) {
$attr = (function($attr){return ""; })()
}
if (!$attr) {
$attr = "no success";
}