PHP code example of cycle / transaction

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

    

cycle / transaction example snippets


use Cycle\Transaction\Internal\TransactionImpl;
use Cycle\Transaction\Transaction;

/**
 * @var \Cycle\ORM\ORMInterface $orm
 * @var \Cycle\Database\DatabaseProviderInterface $dbal
 */
$transaction = new TransactionImpl($orm, $dbal);

use Cycle\Database\DatabaseInterface;
use Cycle\ORM\EntityManagerInterface;

$transaction->transact(function (EntityManagerInterface $em, DatabaseInterface $db): void {
    $em->persist(new User('[email protected]'));

    // The same transaction is visible to raw DBAL operations.
    $db->table('audit')->insertOne(['event' => 'user.created']);
});

$transaction->transact(function (EntityManagerInterface $em): void {
    $em->persist(new User('[email protected]'));

    throw new \DomainException('Something went wrong');
    // Nothing is committed: the new user is rolled back.
});

$user = $transaction->transact(function (EntityManagerInterface $em): User {
    $user = new User('[email protected]');
    $em->persist($user);

    return $user;
});

use Cycle\Transaction\FlushMode;

// Require the callback to flush explicitly; otherwise the transaction fails.
$transaction->transact(
    callback: function (EntityManagerInterface $em): void {
        $em->persist(new User('[email protected]'));
        $em->run(); // explicit flush — without it a TransactionException is thrown
    },
    flush: FlushMode::FailOnPending,
);

use Cycle\Transaction\TransactionMode;

$transaction->transact(
    callback: function (EntityManagerInterface $em): void {
        $em->persist(new User('[email protected]'));
    },
    emMode: TransactionMode::OpenNew,
);

// By connection name.
$transaction->transact(
    callback: fn(EntityManagerInterface $em, DatabaseInterface $db) => $db->getName(),
    source: 'reporting',
);

// By entity class — resolves the connection the entity is mapped to.
$transaction->transact(
    callback: function (EntityManagerInterface $em): void {
        $em->persist(new User('[email protected]'));
    },
    source: User::class,
);