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


use Sbooker\TransactionManager\TransactionHandler;
use Sbooker\TransactionManager\TransactionManager;


$transactionManager = new TransactionManager(new class implements TransactionHandler { ... });

class Entity {
    /**
     * @throws \Exception 
     */  
    public function update(): void { ... }
}

$transactionManager->transactional(function () use ($transactionManager) {
    $transactionManager->persist(new Entity());
});

$transactionManager->transactional(function () use ($transactionManager, $entityId) {
    $entity = $transactionManager->getLocked(Entity::class, $entityId);
    $entity->update(); // if exception throws, transaction will be rolled back
});

$transactionManager->transactional(function () use ($transactionManager, $entityRepository, $criteria) {
    $entity = $entityRepository->getLocked($criteria);
    $entity->update(); // if exception throws, transaction will be rolled back
    $transactionManager->save($entity);
});

final class CommandProcessor {
    private TransactionManager $transactionManager;
    ...
    /** @throws \Exception */
    public function update($entityId): void
    {
        $transactionManager->transactional(function () use ($transactionManager, $entityId) {
            $entity = $transactionManager->getLocked(Entity::class, $entityId);
            $entity->update(); 
        });
    }
}

$commandProcessor = new CommandProcessor($transactionManager);

$transactionManager->transactional(function () use ($transactionManager, $commandId, $commandProcessor) {
    $command = $transactionManager->getLocked(Command::class, $commandId);
   try {
        $commandProcessor->update($command->getEntityId());
        $command->setSuccessExecutionState();
   } catch (\Exception) {
        $command->setFailExecutionState(); 
   }
});

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