vadage/oxidize

一些 Rust 概念的 PHP 实现

v1.0.0 2024-04-06 18:08 UTC

This package is auto-updated.

Last update: 2024-09-06 18:57:51 UTC


README

PHP 对 Rust 建立的一些优秀概念的实现。

Oxidize

Rust 通过设计鼓励开发者正确处理错误和非值。
这有助于减少生产中的非逻辑错误,代码也可能看起来更整洁。

Oxidize 库是用纯 PHP 编写的,并且只 适配 一些概念,这些概念也被 Rust 所使用。方法名称保持相似(snake_case 到 camelCase),以便于使用这两种语言的开发者。
有一些额外的包装方法,例如在 ResultOption 中都使用 andThenContinue() 来消除返回语句。然后将自动返回一个新实例。

安装

composer require vadage/oxidize

无异常

方法中不需要声明抛出异常,这增加了它们未被处理的概率。
这时,Result 就派上用场了,它用 OkError 来表示。在 Error 上调用 unwrap 或在 Ok 上调用 unwrapError 将导致 ValueAccessError

$userResult = $this->userRpc->login($email, $password);
if ($userResult->isOk()) {
    $user = $userResult->unwrap();
    $this->messages->queue(sprintf('Hello %1$s.', $user->getUsername()));
}

空安全

方法返回对象或 null 可能并不总是很明显。
相比于 null,可以使用 Option,它表示两种状态之一(SomeNone)。在 None 上调用 unwrap 将导致 ValueAccessError

$terminationDateOption = $user->getTerminationDate();
if ($terminationDateOption->isSome()) {
    $terminationDate = $terminationDateOption->unwrap();
    $this->messages->queue(sprintf('Your login will be deactivated after %1$s.', $terminationDate->format(DateTimeInterface::RSS)));
}

结果和 Option 的 Monads

Monads 可以通过消除一些 if 语句、变量声明和 unwrap 调用来改善代码的美观。

$this->userRpc->login($email, $password)->andThenContinue(function (User $user) {
    $username = $user->getUsername();

    $user->getTerminationDate()
        ->andThenContinue(function (DateTime $terminationDate) {
            $formattedDate = $terminationDate->format(DateTimeInterface::RSS);
            $this->messages->queue(sprintf('Hello %1$s. Your login will be deactivated after %2$s.', $username, $formattedDate));
        })
        ->orElseContinue(function () {
            $this->messages->queue(sprintf('Hello %1$s.', $username));
        });
});