PHP code example of wangrunxinyes / hyperf-tcc

1. Go to this page and download the library: Download wangrunxinyes/hyperf-tcc library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wangrunxinyes / hyperf-tcc example snippets


use YogCloud\TccTransaction\Example\Test;

   /**
    * @GetMapping(path="nsq")
    */
    public function nsq(RequestInterface $req, ResponseInterface $res)
    {
        $goodsId = $req->input('goods_id', 1);
        $couponId = $req->input('coupon_id', 0);
        $result = (new Test())->handle($goodsId,$couponId);
        return $res->json([
           'code' => 0,
           'data' => $result,
        ]);
    }

use YogCloud\TccTransaction\Tcc;
use YogCloud\TccTransaction\Example\Tcc\GoodsLockTcc;
use YogCloud\TccTransaction\Example\Tcc\CouponLockTcc;
use YogCloud\TccTransaction\Example\Tcc\OrderTcc;
use YogCloud\TccTransaction\Example\Tcc\GoodsSubTcc;
use YogCloud\TccTransaction\Example\Tcc\CouponSubTcc;
use YogCloud\TccTransaction\Example\Tcc\OrderMessageTcc;
use YogCloud\TccTransaction\Example\Tcc\OrderStatisticsTcc;

$goodsId = 1;
$couponId = 0;
$tcc = new Tcc;
$tcc
    ->tcc(1, new GoodsLockTcc($goodsId)) // 商品库存锁定
    ->tcc(2, new CouponLockTcc($couponId)) // 优惠券锁定
    ->tcc(3, new OrderTcc) // 创建订单
    ->tcc(4, new GoodsSubTcc) // 扣减库存
    ->tcc(5, new CouponSubTcc) // 占用优惠券
    ->tcc(6, new OrderMessageTcc) // 创建订单消息
    ->tcc(7, new OrderStatisticsTcc) // 订单统计
    ->rely([          // 配置执行流程
        // 外层步骤是逐步执行的
        // [...] 内层步骤是同步执行的
        [1, 2],       // 1,2 锁定库存, 锁定优惠券
        [3],          // 3 创建订单
        [4, 5, 6, 7], // 4,5,6,7 扣减库存, 占用优惠券, 订单消息, 订单统计
    ])->begin(); // 开启事务

php bin/hyperf.php vendor:publish yogcloud/hyperf-tcc

php bin/hyperf.php migrate
bash
curl http://localhost:9501/index/nsq?goods_id=1&coupon_id=0

{"code":0,"data":{"order":{"order_sn":255041892524236800,"body":"购买桃子","total_fee":"200.00","goods_id":1,"id":2483},"goods":{"id":1,"price":"200.00","name":"桃子","num":9994,"lock":0,"sale":6},"coupon":null}}