定制 krak/effects 二次开发

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

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

krak/effects

Composer 安装命令:

composer require krak/effects

包简介

Safely manage side effects within your domain layer.

README 文档

README

The effects library is a small set of utilities to help enable side effects in code that you expect to remain pure using PHP generators to transfer ownership.

This is helpful in terms of Domain Driven Design and maintaining a pure domain model.

Usage

<?php

use function Krak\Effects\{handleEffects, expect};

// Domain Entity
final class ShoppingCart
{
    public function checkOut(CheckOutShoppingCart $checkOutShoppingCart) {
        // ... build up captueCharge command
        $capturedCharge = expect(CapturedCharge::class, yield new CaptureCharge(/* args */));
    }
}

// Domain Commands/Effects
final class CheckOutShoppingCart {}
final class CaptureCharge {}
final class CapturedCharge {}

// Application Command Handler
final class HandleCheckOutShoppingCart
{
    public function __invoke(CheckOutShoppingCart $checkOutShoppingCart): void {
        $shoppingCart = $this->shoppingCarts->get($checkOutShoppingCart->shoppingCart());
        handleEffects($shoppingCart->checkOut($checkOutShoppingCart), [
            CaptureCharge::class => function(CaptureCharge $captureCharge) {
                return $this->paymentGateway->capture($captureCharge); // returns a CapturedCharge instance
            }
        ]);
    }
}

How it Works

This works by leveraging the fact that PHP generators allow sending values back to a yielded result. The handleEffects function simply just iterates over the domain method pulling all of the commands, passing them to the command handler map, and then taking the responses and sending them back to the domain method.

The expect function is just a safety helper to provide type auto completion and assert the expected class in case there was a mapping error to make debugging a bit nicer. It's technically not needed, so if you don't care about auto-completion help with psalm and PHPStorm, then feel free to just use the yield keyword without the expect function.

Nested Effects with yield from

If you end up needing to raise a few effects with one method, it may make sense to have specific methods used to manage and raise those effects.

You can use the yield from statement to raise effects from child methods. here's an example:

final class Product
{
    public function checkout() {
        yield from $this->raiseEffects();
    }
    
    private function raiseEffects() {
        $result = yield new Effect1();
    }
}

Prewk\Result Integration

If you are working with more complex domain methods/services, it can be helpful to structure individual parts of the code in separate functions that return results and can short circuit operations like one would use with a normal Result class.

Let's see how we can acheive that with the MapEffectResults class.

use Prewk\Result;
use Krak\Effects\Bridge\Result\MapEffectResults;
use function Krak\Effects\expect;

final class Product
{
    public function syncInventory() {
        expect(Result::class, yield from MapEffectResults::map(
            $this->fetchInventoryFromERP(),
            $this->fetchPricingRules(),
            $this->pushInventoryToThirdParty()
        ))->mapErr(function() {
            // set some error state maybe.
        })->map(function() {
            // set some success state maybe.
        });
    }
    
    public function fetchInventoryFromERP(){
        return function() {
            return expect(Result::class, yield new FetchInventoryFromERP($this->productId));
        };
    }
    
    public function fetchPricingRules(){
        return function(InventoryFromERP $inventoryFromERP) {
            return expect(Result::class, yield new FetchPricingRulesForProduct($this->productId))
                ->map(function(PricingRules $pricingRules) use ($inventoryFromERP) {
                    return [$inventoryFromERP, $pricingRules];
                });
        };
    }
    
    public function pushInventoryToThirdParty() {
        return function(array $tup) {
            [$inventoryFromERP, $pricingRules] = $tup;
            // calculate final inventory using special logic
            return expect(Result::class, yield new PushInventoryToThirdParty($finalInventory));
        };
    }
}

// in some application service
\Krak\Effects\handleEffects($product->syncInventory(), []); // with handlers accordingly

Installation

Install with composer at krak/effects

Inspiration

This design is inspired from the Elm language design around maintaining pure application code while leaving side effects to be managed by the runtime.

Here are some other helpful resources around domain model purity and side effects:

krak/effects 适用场景与选型建议

krak/effects 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.39k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2021 年 01 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-01-06