PHP code example of sbooker / transaction-manager

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

    

sbooker / transaction-manager example snippets


// bootstrap.php или ваш DI-контейнер
/** @var Sbooker\DoctrineTransactionHandler\TransactionHandler $transactionHandler */
$transactionManager = new Sbooker\TransactionManager\TransactionManager($transactionHandler);

// src/Products/Application/Handler.php
final class Handler
{
    private TransactionManager $transactionManager;
    // ...

    public function handle(Command $command): void
    {
        $this->transactionManager->transactional(function () use ($command): void {
            $product = new Product(/* ... */);
            // Регистрируем новую сущность для сохранения
            $this->transactionManager->persist($product);
        });
        // После выхода из этого блока, внутреннее состояние менеджера полностью очищено.
    }
}

// src/Products/Application/Handler.php
final class Handler
{
    private TransactionManager $transactionManager;
    // ...

    public function handle(Command $command): void
    {
        $this->transactionManager->transactional(function () use ($command): void {
            // 1. Получаем сущность с блокировкой. Это единственный способ.
            /** @var Product|null $product */
            $product = $this->transactionManager->getLocked(Product::class, $command->getProductId());

            if (null === $product) {
                throw new Exception('Product not found.');
            }

            // 2. Выполняем бизнес-логику
            $product->changeName($command->getNewName());

            // 3. НЕ НУЖНО вызывать persist() или save()!
            // Сущность, полученная через getLocked(), уже находится под управлением Unit of Work.
        });
        // Здесь Unit of Work также полностью очищен.
    }
}

// bootstrap.php или ваш DI-контейнер
$loggingProcessor = new LoggingProcessor($logger);
$transactionManager = new Sbooker\TransactionManager\TransactionManager(
    $transactionHandler,
    $loggingProcessor
);

$entityId = ...;
$transactionManager->transactional(function () use ($transactionManager, $entityId) {
    $entity = new SomeEntity($entityId);
    $transactionManager->persist($entity);
    
    // Depends on TransactionHandler implementation $persistedEntity may be null in same transaction with persist
    $persistedEntity = $transactionManager->getLocked($entityId);    
}