承接 bosunski/results 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

bosunski/results

Composer 安装命令:

composer require bosunski/results

包简介

Rust-like Result/Option utility for PHP

README 文档

README

Results is a PHP simple (dependency-free) library that provides a set of helper functions and classes for handling optional values and results of operations. It is inspired by the Option and Result types in Rust. The implementation itself is based on the TypeScript implementation called ts-results.

Installation

You can install the library through Composer:

composer require bosunski/results

Usage

Demo

You can try the package in this Playground

Option

The Option type represents an optional value: every Option is either Some and contains a value, or None, and does not.

<?php

use function Bosunski\Results\Option;

$some = Option('value'); // Some
$none = Option(null); // None

Result

The Result type is a type that represents either success (Ok) or failure (Err).

<?php

use function Bosunski\Results\Result;

$ok = Result('value'); // Ok
$err = Result(new Exception('error')); // Err

Helper Functions

The library provides a set of helper functions for creating Option and Result instances:

  • Some(mixed $value): Some
  • None(): None
  • Option(mixed $value): Option
  • Ok(mixed $value): Ok
  • Err(Throwable $e): Err
  • Result(mixed $value): Ok|Err
  • wrap(callable $fn): Result

Examples

Optional values and results in PHP can be represented using the Option and Result types provided by the Results library. Here are some examples:

<?php

use function Bosunski\Results\Option;
use function Bosunski\Results\Result;

// Options
$some = Option('value'); // Some
$none = Option(null); // None

// Results
$ok = Result('value'); // Ok
$err = Result(new Exception('error')); // Err

In the above examples:

  • Option('value') creates an Option that contains a value (referred to as Some).
  • Option(null) creates an Option that does not contain a value (referred to as None).
  • Result('value') creates a Result that represents a successful operation (Ok).
  • Result(new Exception('error')) creates a Result that represents a failed operation (Err).

Let's dive into more complex examples of using the Option and Result types in PHP.

Consider a scenario where we have a function that may or may not return a value. We can use the Option type to handle this uncertainty.

<?php

use Bosunski\Results\Option as OptionInterface;
use function Bosunski\Results\Option;

function findUserById($id): OptionInterface {
    // Assume getUserFromDatabase is a function that returns a User object if found, null otherwise
    $user = getUserFromDatabase($id);
    
    return Option($user);
}

$userOption = findUserById(123);

// We can then handle the optional value using the methods provided by the Option type
if ($userOption->isSome()) {
    $user = $userOption->unwrap();
    // Do something with the user
} else {
    // Handle the case where no user was found
}

// You can also do this
$user = $userOption->unwrap() // Throws error if null

Now, let's consider a scenario where we have a function that can either succeed or fail. We can use the Result type to handle this.

<?php

use Bosunski\Results\Result\Result as ResultInterface;
use function Bosunski\Results\Result;

function divide(int $numerator, int $denominator): ResultInterface {
    if ($denominator == 0) {
        return Err(new Exception("Cannot divide by zero"));
    } else {
        return Ok($numerator / $denominator);
    }
}

$result = divide(10, 0);

// We can then handle the result using the methods provided by the Result type
if ($result->isOk()) {
    $value = $result->unwrap();
    // Do something with the value
} else {
    $error = $result->unwrapErr();
    // Handle the error
}

// You can also do this
$user = $result->unwrap() // Throws error if an error is present

In these examples, the Option and Result types provide a way to handle optional values and the results of operations in a safe and expressive manner.

The wrap Function

The wrap function is a utility function provided by the library. It is designed to handle operations that can throw an error. The wrap function executes a callable and returns its result wrapped in a Result object. If the callable function throws an exception, the wrap function catches it and returns an Err object containing the exception.

Important

The wrap function will only catch instances of Throwable. If your function raises something like a fatal error it will not be caught by wrap.

Here's an example of how you might use the wrap function:

<?php

use function Bosunski\Results\wrap;

function mightThrowException(): int {
    if (rand(0, 1) === 1) {
        throw new Exception('An error occurred');
    }

    return 42;
}

$result = wrap(mightThrowException(...));

if ($result->isOk()) {
    echo "Success: " . $result->unwrap();
} else {
    echo "Error: " . $result->unwrapErr()->getMessage();
}

In this example, mightThrowException is a function that might throw an exception. We pass this function to wrap, which executes it, catch any error and wraps the result in a Result object. We then check if the result is an instance of Ok or Err and handle it accordingly.

The wrap function provides a safe and expressive way to handle operations that can throw errors, allowing you to focus on your application logic rather than error handling when you don't need to.

Contributing

Setting up the project

You can install development dependencies by running:

composer install

Running tests

composer run test

License

This project is licensed under the MIT License.

bosunski/results 适用场景与选型建议

bosunski/results 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.21k 次下载、GitHub Stars 达 6, 最近一次更新时间为 2023 年 12 月 29 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「exception」 「error」 「result」 「rust」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 bosunski/results 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 bosunski/results 我们能提供哪些服务?
定制开发 / 二次开发

基于 bosunski/results 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.21k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 3
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 6
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-12-29