tekord/php-result

受Rust编程语言启发的PHP结果对象

v0.9-beta 2024-05-30 08:56 UTC

This package is auto-updated.

Last update: 2024-08-30 09:28:00 UTC


README

受Rust编程语言启发的PHP结果对象。

当您希望错误返回而不是抛出时,该对象非常有用。几个辅助函数使使用变得简单。

PHP Version Support Packagist version License

安装

使用Composer安装包

composer require tekord/php-result

用法

示例

class ErrorInfo {
    public $code;
    public $message;
    public $context;

    public function __construct($code, $message, $context = []) {
        $this->code = $code;
        $this->message = $message;
        $this->context = $context;
    }
}

function createOrder(User $user, $products): Result {
    if (!$user->isVerified())
        return Result::fail(
            new ErrorInfo("unverified_user", "Unverified users are not allowed to order", [
                'user' => $user
            ])
        );
        
    if ($user->hasDebts())
        return Result::fail(
            new ErrorInfo("user_has_debts", "Users with debts are not allowed to order new items", [
                'user' => $user
            ])
        );
        
    if ($products->isEmpty())
        return Result::fail(
            new ErrorInfo("no_products", "Products cannot be empty")
        );
  
    // Create a new order here...
    
    return Result::success($newOrder);
}

// ...

$createOrderResult = createOrder($user, $productsFromCart);

// This will throw a panic exception if the result contains an error
$newOrder = $createOrderResult->unwrap();
   
// - OR -

// You can check if the result is OK and make a decision on it
if ($createOrderResult->isOk()) {
    $newOrder = $createOrderResult->ok;
    
    // ...
}
else {
    throw new DomainException($createOrderResult->error->message);
}

// - OR -

// Get a default value if the result contains an error
$newOrder = $createOrderResult->unwrapOrDefault(new Order());

您可以扩展Result类以覆盖异常类(注意phpDoc)

/**
 * @tempate OkType
 * @tempate ErrorType
 *
 * @extends Result<OkType, ErrorType>
 */
class CustomResult extends Result {
    static $panicExceptionClass = DomainException::class;
}

测试

composer test

安全

如果您发现任何安全相关的问题,请通过电子邮件cyrill@tekord.space联系,而不是使用问题跟踪器。