ganglio/please

PHP 函数性尝试

v1.1.0.2 2016-03-03 15:10 UTC

This package is not auto-updated.

Last update: 2024-09-20 21:58:27 UTC


README

try/catch 的功能性和礼貌实现

Latest Stable Version Build Status codecov.io Code Climate Scrutinizer Code Quality License

示例

让我们从简单的事情开始

$inverse = function ($v) {
  if (empty($v)) {
    throw new \Exception("Division by zero");
  }

  return 1/$v;
}

我们通常会这样做

try {
  $result = $inverse(0);
} catch (\Exception $e) {
  error_log("Error: " . $e->getMessage());
}

使用 Please 我们这样做

$result = new Please($inverse, 0);

现在我们可以检查可调用是否成功完成。

if ($result->isSuccess) {
  echo "The result is: " . $result->get();
}

或者我们可以使用回调(更优雅)

$result->onSuccess(function ($v) {
  echo "The result is: " . $v;
});

不幸的是,我们尝试除以零,因此可调用没有成功。我们可以获取异常

$exception = $result->get();

或者用回调处理它

$result->onFailure(function ($e) {
  error_log("Error: " . $e->getMessage());
});

我们甚至可以使用 on 传递两个回调

$result->on(
  function ($v) {
    echo "Result: " . $v;
  },
  function ($e) {
    echo "Error: " . $e->getMessage();
  }
);

onSuccessonFailureon 返回一个新实例的 Please,它包装了回调。这样,如果我们想,我们可以这样做

echo (new Please($inverse, $unknown_divisor))
  ->on(
    function ($v) {
      return "Result: " . $v;
    },
    function ($e) {
      return "Error: " . $e->getMessage;
    }
  )->get();

现在让我们来看一个稍微复杂一点的例子

让我们想象我们有一个字符串数组,其中一些是 json 编码的对象

$strings = [
  'not json',
  '{"a":3,"b":4}',
  'still not json',
  '{"c":5}',
];

和一个包装 json_decode 的错误时抛出异常的包装器

$json_decoder_exception = function ($string) {
  $out = json_decode($string);
  if (json_last_error() != JSON_ERROR_NONE) {
    throw new \Exception("Invalid JSON");
  }
  return $out;
};

然后我们可以使用 Please 解码和过滤它们

$results = array_filter(
  array_map(function ($s) use ($json_decoder_exception) {
    return new Please($json_decoder_exception, $s);
  }, $strings),
  function ($e) {
    return $e->isSuccess;
  }
);