PHP code example of maatify / persistence

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

    

maatify / persistence example snippets


use Maatify\Persistence\Pdo\Ordering\ScopedOrderingConfig;
use Maatify\Persistence\Pdo\Ordering\ScopedOrderingManager;

// 1. Configure the ordering behavior for a table
$config = new ScopedOrderingConfig(
    table: 'maa_shipping_rates',
    scopeColumn: 'method_id', // Use null for global ordering
    idColumn: 'id',
    orderColumn: 'display_order',
    deletedAtColumn: 'deleted_at', // Use null if soft-deletes are not used
    // Set nullableScope: true when NULL is a real scope (for example, roots).
    nullableScope: false,
    // Optional: update this column atomically with a successful move.
    updatedAtColumn: null,
);

$ordering = new ScopedOrderingManager();

// 2. Get the next position for a new insert. getNextPosition() is a plain,
// lock-free read: serialize concurrent writers yourself, for example by locking
// a parent row before the transaction's first non-locking read (see
// "Critical Runtime Behavior"). Here the caller owns the transaction.
$pdo->beginTransaction();

try {
    // Serialization precondition: the parent row exists, and EVERY writer that
    // allocates a position in this scope takes this same lock first, before any
    // non-locking read of its transaction. Without an existing, selected row
    // nothing is locked.
    $parentLock = $pdo->prepare('SELECT `id` FROM `maa_shipping_methods` WHERE `id` = :id FOR UPDATE');
    $parentLock->execute(['id' => 2]);

    if ($parentLock->fetchColumn() === false) {
        throw new RuntimeException('Parent row 2 does not exist, so nothing was locked.');
    }

    $nextPosition = $ordering->getNextPosition(
        pdo: $pdo,
        config: $config,
        scopeValue: 2, // Use null for global ordering
    );

    // Insert on the same connection and in the same transaction, then commit
    // (add your table's other columns).
    $pdo->prepare('INSERT INTO `maa_shipping_rates` (`method_id`, `display_order`) VALUES (:method_id, :position)')
        ->execute(['method_id' => 2, 'position' => $nextPosition]);

    $pdo->commit();
} catch (Throwable $throwable) {
    // Best effort: a failing cleanup must never replace the original exception
    // (after a deadlock, 1213, the server has already rolled the transaction
    // back and inTransaction() can be stale, so rollBack() itself may throw).
    try {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
    } catch (Throwable) {
        // Ignored on purpose; the original $throwable is rethrown below.
    }

    throw $throwable;
}

// 3. Move an existing row within its scope
// Returns false when the row is missing or the final update changed nothing; in
// a caller-owned transaction check it before commit() (see "Who rolls back").
$success = $ordering->moveWithinScope(
    pdo: $pdo,
    config: $config,
    scopeValue: 2, // Use null for global ordering
    id: 15,
    newOrder: 4,
    // Required when updatedAtColumn is configured.
    updatedAtValue: null,
);

use Maatify\Persistence\Pdo\Transaction\PdoDeadlockRetryTransactionRunner;

$transactions = new PdoDeadlockRetryTransactionRunner($pdo);

$transactions->run(function () use ($pdo, $ordering, $config): void {
    $nextPosition = $ordering->getNextPositionForUpdate(
        pdo: $pdo,
        config: $config,
        scopeValue: 2, // Use null for global ordering
    );

    // Insert the new row at $nextPosition using the same PDO connection.
});

use Maatify\Persistence\Pdo\Transaction\PdoDeadlockRetryTransactionRunner;

$transactions = new PdoDeadlockRetryTransactionRunner($pdo);

$transactions->run(function () use ($pdo, $ordering, $config): void {
    $pdo->prepare('UPDATE `consumer_table` SET `status` = :status WHERE `id` = :id')
        ->execute(['status' => 'ready', 'id' => 10]);

    // false (row missing, or the final update changed nothing) must not be
    // ignored: throwing makes the runner roll back the whole owned transaction.
    if ($ordering->moveWithinScope($pdo, $config, 2, 15, 4) === false) {
        throw new RuntimeException('moveWithinScope() returned false.');
    }
});

$transactions = new PdoDeadlockRetryTransactionRunner($pdo, maxDeadlockRetries: 3);

use Maatify\Persistence\Pdo\Pagination\PaginationConfig;
use Maatify\Persistence\Pdo\Pagination\PageRequest;
use Maatify\Persistence\Pdo\Pagination\PdoPaginationQueryDescriptor;
use Maatify\Persistence\Pdo\Pagination\PdoPaginator;
use Maatify\Persistence\Pdo\Pagination\SortWhitelist;
use Maatify\Persistence\Pdo\Pagination\SortDirectionEnum;

$config = new PaginationConfig(
    defaultPerPage: 10,
    maxPerPage: 100,
    minPerPage: 1,
    sortWhitelist: new SortWhitelist([
        'id' => 'id',
        'created' => 'created_at',
        'name' => 'user_name',
    ]),
    defaultSortBy: 'created',
    defaultSortDirection: SortDirectionEnum::DESC,
    tieBreakerSortBy: 'id',
    tieBreakerDirection: SortDirectionEnum::DESC
);

$query = new PdoPaginationQueryDescriptor(
    totalSql: 'SELECT COUNT(*) FROM users',
    totalParams: [],
    filteredCountSql: 'SELECT COUNT(*) FROM users WHERE status = :status',
    filteredCountParams: ['status' => 'active'],
    dataSql: 'SELECT id, user_name, created_at FROM users WHERE status = :status',
    dataParams: ['status' => 'active']
);

$request = new PageRequest(page: 2, perPage: 15, sortBy: 'name', sortDirection: 'ASC');

$paginator = new PdoPaginator();
$result = $paginator->paginate(
    pdo: $pdo,
    query: $query,
    request: $request,
    config: $config,
    mapper: fn(array $row) => (object) $row
);

Maatify\Persistence\Pdo\Ordering\ScopedOrderingConfig;
Maatify\Persistence\Pdo\Ordering\ScopedOrderingManager;
Maatify\Persistence\Pdo\Transaction\TransactionRunnerInterface;
Maatify\Persistence\Pdo\Transaction\PdoTransactionRunner;
Maatify\Persistence\Pdo\Transaction\SavepointTransactionRunnerInterface;
Maatify\Persistence\Pdo\Transaction\PdoSavepointTransactionRunner;

Maatify\Persistence\Pdo\Pagination\PageRequest;
Maatify\Persistence\Pdo\Pagination\SortDirectionEnum;
Maatify\Persistence\Pdo\Pagination\SortWhitelist;
Maatify\Persistence\Pdo\Pagination\PaginationConfig;
Maatify\Persistence\Pdo\Pagination\PdoPaginationQueryDescriptor;
Maatify\Persistence\Pdo\Pagination\PageResult;
Maatify\Persistence\Pdo\Pagination\PdoPaginator;

// Exceptions
Maatify\Persistence\Exception\PersistenceException;
Maatify\Persistence\Exception\InvalidOrderingConfigurationException;
Maatify\Persistence\Exception\InvalidOrderingOperationException;
Maatify\Persistence\Exception\OrderingTransactionException;
Maatify\Persistence\Exception\InvalidPaginationConfigurationException;
Maatify\Persistence\Exception\InvalidPaginationQueryException;
Maatify\Persistence\Exception\PaginationExecutionException;
Maatify\Persistence\Exception\TransactionExecutionException;

Maatify\Persistence\Pdo\Transaction\PdoDeadlockRetryTransactionRunner;
Maatify\Persistence\Pdo\Transaction\PdoDeadlockRetrySavepointTransactionRunner;
Maatify\Persistence\Exception\InvalidTransactionConfigurationException;
bash
php examples/next-position/01_allocate_and_insert.php
bash
php examples/move-within-scope/01_move_after_older_snapshot.php
bash
php examples/deadlock-retry/01_owned_transaction_replay.php
php examples/deadlock-retry/02_caller_owned_no_replay.php