Skip to content

Transactons

Jason Napolitano edited this page Sep 15, 2023 · 7 revisions

Working with transactions is extremely easy using DatabaseFactory. In order to use transactions, you need to add the HasTransact trait to your entity class:

W.I.P

Entity Class

use DatabaseFactory\ORM;

class User extends DatabaseFactory\Entity
{
    use ORM\HasTransact;
}

Transactions

Now, you may use the transaction system on an entity class. DatabaseFactory uses a promise-like system to interact with transacted data. It s important to note that each call to then() returns the current $builder instance for further computational instructions. This allows you to work with the same dataset, throughout different sequences of code. After all is said and done, the transaction is completed and that $builder instance can no longer be interacted with.

$transact = User::transact(function (Builder $builder) {
	$builder->select('name');
	$builder->where('id', '<>', 1);
	$builder->limit(5);
});

then()

$transact->then(fn(DatabaseFactory\Builder $builder) => dump($builder->get()))
	 ->then(fn(DatabaseFactory\Builder $builder) => dump($builder->toSQL()));

stop()

$transact->stop(fn(DatabaseFactory\Builder $builder) => dump($builder));

error()

You can also catch any errors, and do something with them by calling the error() method. Ultimately, an error is a returned PDOException and can be interacted with as such.

$transact->error(fn(\PDOException $error) => dump($error->getMessage()))
Clone this wiki locally