sk / transaction

在多个动作期间处理事务的库

v1.0.0 2016-11-20 10:10 UTC

This package is auto-updated.

Last update: 2024-09-07 01:07:59 UTC


README

Build Status SensioLabsInsight Coverage Status

介绍

这个库声称提供了一个简单的方法来在几乎所有事情中实现安全的事务。

安装

此库可以通过composer轻松安装

composer require sk/transaction

或直接将其添加到您的composer.json文件中。

用法

作为一个基本的用法示例,CallbackTransaction被用来演示在三次API调用期间的行为

<?php
use SK\Transaction\CallbackTransaction;
use SK\Transaction\Exception\RollbackException;
use SK\Transaction\ParameterBag;
use Acme\Api1Client;
use Acme\Api2Client;
use Acme\Api3Client;

$api1Client = new Api1Client();
$callbackTransaction = new CallbackTransaction(
    // Do something important
    function (ParameterBag $parameters) use ($api1Client) {
        $api1Client->doSomethingImportant($parameters);
    },
    // Roll back if an exception in one of the next transaction(s) occurred.
    // For more information see interface \SK\Transaction\OwnExceptionRollback
    function () use ($api1Client) {
        $api1Client->rollback();
    }
);

$api2Client = new Api2Client();
$callbackTransaction2 = new CallbackTransaction(
    function (ParameterBag $parameters = null) use ($api2Client) {
        $api2Client->doSomethingImportant($parameters);
    },
    function () use ($api2Client) {
        $api2Client->rollback();
    }
);

$api3Client = new Api3Client();
$callbackTransaction2 = new CallbackTransaction(
    function (ParameterBag $parameters) use ($api3Client) {
        $api3Client->doSomethingImportant($parameters);
    },
    function () use ($api3Client) {
        // This will never executed. For more information see \SK\Transaction\OwnExceptionRollback
        $api3Client->rollback();
    }
);

$callbackTransaction->append($callbackTransaction2);
$callbackTransaction->append($callbackTransaction3);
// or
// $callbackTransaction2->append($callbackTransaction3);

try {
    $callbackTransaction->execute();
} catch (RollbackException $e) {
    // Something really bad happens
    // But you can get the Exception which causes the rollback
    $e->getOrigin();
    // And you can get the exception which occurred during rollback
    $e->getPrevious();
} catch (\Exception $e) {
    // An exception occurred, but all executed actions was rolled back successfully
}

待办事项

  • 编写更多文档
  • 修复错别字

许可证

此库采用MIT许可证。请参阅LICENCE文件中的完整许可证。