tito10047/doctrine-transaction

管理 doctrine 事务的库

0.1.1 2024-09-23 07:59 UTC

This package is auto-updated.

Last update: 2024-09-23 08:12:40 UTC


README

Tests Coverage Status

Doctrine 事务

当你在应用程序中使用 Repository 类而不直接使用 EntityManager 时,你无法在 Repository 类上使用事务方法。此包允许你在应用程序的任何地方使用事务。

当你在同一个事务中需要使用多个连接时,此包也非常有用。

设置

composer require tito10047/doctrine-transaction

尝试它

#service.yaml
services:
    Tito10047\DoctrineTransaction\TransactionManagerInterface:
        class: Tito10047\DoctrineTransaction\TransactionManager
use Tito10047\DoctrineTransaction\TransactionManager;

class MyService
{

    public function __construct(private readonly TransactionManagerInterface $tm)
    {
    }

    public function myMethod()
    {
        $transaction = $this->tm->beginTransaction();
        try {
            // Your code
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollback();
            throw $e;
        }
    }
    
    public function myBatchMethod() {
        $transaction = $this->tm->beginTransaction();
        try {
            for($i = 0; $i < 100; $i++) {
                $myEntity = new MyEntity();
                if ($transaction->batchCommit($i,10)){
                    $transaction->clear(MyEntity::class);
                }
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollback();
            throw $e;
        }    
    }
    
    public function myCallbacksMethod() {
        $transaction = $this->tm
            ->beginTransaction()
            ->addCommitHandler(function() {
                // Your code
            })
            ->addRollbackHandler(function() {
                // Your code
            });
        try {
            for($i = 0; $i < 100; $i++) {
                $myEntity = new MyEntity();
                if ($transaction->batchCommit($i,10)){
                    $transaction->clear(MyEntity::class);
                }
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollback();
            throw $e;
        }
    }
    
    public function multipleConnections() {
        $transaction = $this->tm->beginTransaction('connection1','connection2');
        try {
            // Your code
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollback();
            throw $e;
        }
    }
}