PHP code example of kang-babi / transactions

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

    

kang-babi / transactions example snippets


use KangBabi\Transactions\Transaction;

$result = Transaction::start()
    ->try(fn (): string => 'Hello, World!')
    ->run();

// $result === 'Hello, World!'

use KangBabi\Transactions\Transaction;

$result = Transaction::start()
    ->try(function (): string {
        throw new RuntimeException('Operation failed.');
    })
    ->catch(RuntimeException::class, function (RuntimeException $exception): string {
        return 'Handled: ' . $exception->getMessage();
    })
    ->run();

// $result === 'Handled: Operation failed.'

use KangBabi\Transactions\Transaction;

$result = Transaction::start()
    ->try(function (): string {
        throw new InvalidArgumentException('Invalid input.');
    })
    ->catch(InvalidArgumentException::class, fn (InvalidArgumentException $exception): string => $exception->getMessage())
    ->catch(RuntimeException::class, fn (RuntimeException $exception): string => $exception->getMessage())
    ->run();

// $result === 'Invalid input.'

use KangBabi\Transactions\Transaction;

$result = Transaction::start()
    ->try(function (): string {
        throw new RuntimeException('Operation failed.');
    })
    ->catch(RuntimeException::class, fn (RuntimeException $exception): string => 'Recovered')
    ->finally(function (): void {
        echo "Workflow completed.\n";
    })
    ->run();

// Prints: Workflow completed.
// $result === 'Recovered'

use KangBabi\Transactions\Transaction;

final class ExampleService
{
    /** @return array{success: bool, message: string, status: string} */
    public static function execute(bool $shouldFail): array
    {
        return Transaction::start()
            ->try(function () use ($shouldFail): array {
                if ($shouldFail) {
                    throw new RuntimeException('Operation failed.');
                }

                return [
                    'success' => true,
                    'message' => 'Operation completed.',
                    'status' => 'success',
                ];
            })
            ->catch(RuntimeException::class, function (RuntimeException $exception): array {
                return [
                    'success' => false,
                    'message' => $exception->getMessage(),
                    'status' => 'error',
                ];
            })
            ->run();
    }
}