PHP code example of tito10047 / doctrine-transaction

1. Go to this page and download the library: Download tito10047/doctrine-transaction 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/ */

    

tito10047 / doctrine-transaction example snippets


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;
        }
    }
}