A model transaction helps to maintain the integrity of the database after the operations such as insert/delete/update/rollback etc. Transaction checks whether the operations are successfully completed or not before committing the database.
Transactions are of 3 types:
- Manual Transactions
- Implicit Transactions
- Isolated Transactions
Manual Transactions
This method is used when there is only one connection and easy transaction. This transaction can be created by just moving the current connection into transaction mode and then commit or rollback the operation whether it is successful or not.
Implementation
<?php
use Phalcon\Mvc\Controller;
class Cars extends Controller
{
public function saveAction()
{
// Start a transaction
$this->db->begin();
$cars = new Cars();
$car->name = 'Gallardo';
$car->created_at = date('Y-m-d');
// The model failed to save, so rollback the transaction
if ($car->save() === false) {
$this->db->rollback();
return;
}
$carprice= new CarPrice();
$carprice ->car_id = $car->id;
$ carprice ->type = 'head';
// The model failed to save, so rollback the transaction
if ($carprice ->save() === false) {
$this->db->rollback();
return;
}
// Commit the transaction
$this->db->commit();
}
}
Output:
Implicit Transactions
Implicit transaction ensures that the data is stored correctly.
Implementation
<?php
$carprice = new CarPrice();
$carprice->type = 'head';
$car = new Cars();
$car->name = 'Gallardo';
$car->created_at = date('Y-m-d');
$car->carprice = $carprice;
// Creates an implicit transaction to store both records
$car->save();
Isolated Transactions
Isolated transactions are executed in a new connection ensuring that all the generated SQL, virtual foreign key checks and business rules are isolated from the main connection.
Implementation
<?php
use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
try {
// Create a transaction manager
$manager = new TxManager();
// Request a transaction
$transaction = $manager->get();
$car = new Car();
$car->setTransaction($transaction);
$car->name = 'Gallardo';
$car->created_at = date('Y-m-d');
if ($car->save() === false) {
$transaction->rollback(
'Cannot save car?
);
}
$carprice = new CarPrice();
$carprice->setTransaction($transaction);
$carprice->car_id = $car->id;
$carprice->type = 'head';
if ($carprice->save() === false) {
$transaction->rollback(
'Cannot save car price'
);
}
$transaction->commit();
} catch (TxFailed $e) {
echo 'Failed, reason: ', $e->getMessage();
}
Leave a Reply