定制 shipsaas/never-throw 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

shipsaas/never-throw

Composer 安装命令:

composer require shipsaas/never-throw

包简介

Response-first over Throw. PHP NeverThrow library sample implementation

README 文档

README

codecov Build & Test (PHP 8.1, 8.2)

Provide a strictly typed way to deal with Success & Error Outcomes for your PHP applications.

Inspired by NeverThrow so here we are with a simple implementation of NeverThrow from PHP.

Throwing and catching is very similar to using goto statements - in other words; it makes reasoning about your programs harder. Secondly, by using throw you make the assumption that the caller of your function is implementing catch. This is a known source of errors. Example: One dev throws and another dev uses the function without prior knowledge that the function will throw. Thus, and edge case has been left unhandled and now you have unhappy users, bosses, cats, etc.

With all that said, there are definitely good use cases for throwing in your program. But much less than you might think.

TL;DR: no throw = happier life & application. Fewer errors on production & increase the DRY & reusable things in your PHP apps.

Supports

PHP 8.2+

Installation

composer require shipsaas/never-throw

Top-Level API

We provide 2 main classes:

  • Ok
  • Err

You can use them immediately in your code, but we recommend to create your own Success & Error classes to make it more readable and IDE-friendly.

Usage

Create your success & error data classes

class BookShipperOkData
{
    public function __construct(
        public Booking $booking
    ) {}
}

enum BookingErrors {
    case NO_SHIPPER_AVAILABLE;
    case OVERWEIGHT_PACKAGE;
    case INVALID_ADDRESS;
}

// Error
class BookShipperErrorData
{
    public function __construct(
        public BookingErrors $code
    ) {}
}

Returns the Result in your business logic

use NeverThrow\Ok;
use NeverThrow\Err;
use NeverThrow\ResultInterface;

/**
 * @return ResultInterface<BookShipperOkData, BookShipperErrorData>
 */
public function createBooking(User $user, BookingOrder $order): ResultInterface
{
    $hasAnyShipperAvailable = $this->shipperService->hasAnyShipperAvailable();
    if (!$hasAnyShipperAvailable) {
        return new Err(BookingErrors::NO_SHIPPER_AVAILABLE);
    }
    
    $isOverweight = !$this->weightService->isValid($order);
    if ($isOverweight) {
        return new Err(BookingErrors::OVERWEIGHT_PACKAGE);
    }
    
    $booking = $this->book($user, $order);
   
    return new Ok($booking);
}

Check the Response

$bookingResult = $this->service->createBooking($user, $order);

if ($bookingResult->isError()) {
    $errorCode = $bookingResult->unwrapErr()->code;

    // handle error
    return showError(match ($errorCode) {
        BookingErrors::NO_SHIPPER_AVAILABLE => 'No shipper available at the moment. Please wait',
        BookingErrors::OVERWEIGHT_PACKAGE => 'Your package is overweight',
    });
}

return showBooking([
    'booking' => $bookingResult->unwrapOk()->booking,
]);

Conclusion

As you can see with the above code, there are:

  • no try/catch, 0 try/catch abuse
  • no exception, never
  • explicit return types & information.

It would bring the development truly awesome and no pain.

With strictly typed return types, developers can know what is going on when using services/libraries (thus makes the reusable better).

And it makes us worry-free about wrapping things in try/catch blocks.

Let us don't abuse/overuse Exceptions, they should be only used for unexpected situations.

(Additional thoughts: Exceptions are expensive, way more expensive than a simple Error response)

Additional notes

function transfer(): Transaction
{
    if (!$this->hasEnoughBalance()) {
        throw new InsufficientBalanceError();
    }
    
    if (!$this->isValidRecipient()) {
        throw new InvalidRecipientError();
    }
    
    if (!$this->isValidTransferAmount()) {
        throw new InvalidTransferMoneyError();
    }
    
    $transaction = $this->transferService->transfer(...);
    if (!$transaction) {
        throw new TransferFailedError();
    }
    
    return $transaction;
}

Most of this function is actually about the things that can go wrong, but our types only inform us of the successful path. That means 4/5ths of the function's output is untyped!

The above "exceptions" or "errors" aren't really exceptions or errors at all. They are outcomes. They are predictable, reasonable parts of our system. My heuristic is, if they are something a good product manager would care about, they are not exceptions, and you shouldn't throw them!

Exceptions are unpredictable things we cannot reasonably plan for, that the system should not attempt recovery from, and we should not route to the user.

License

MIT License

shipsaas/never-throw 适用场景与选型建议

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

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

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

围绕 shipsaas/never-throw 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 4.81k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 8
  • 点击次数: 7
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 8
  • Watchers: 0
  • Forks: 1
  • 开发语言: PHP

其他信息

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