Model Transactions


Transactions - 图1

Overview

When a process performs multiple database operations, it might be important that each step is completed successfully so that data integrity can be maintained. Transactions offer the ability to ensure that all database operations have been executed successfully before the data is committed to the database.

Transactions in Phalcon allow you to commit all operations if they were executed successfully or rollback all operations if something went wrong.

Manual Transactions

If an application only uses one connection and the transactions are not very complex, a 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:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class RobotsController extends Controller
  4. {
  5. public function saveAction()
  6. {
  7. // Start a transaction
  8. $this->db->begin();
  9. $robot = new Robots();
  10. $robot->name = 'WALL-E';
  11. $robot->created_at = date('Y-m-d');
  12. // The model failed to save, so rollback the transaction
  13. if ($robot->save() === false) {
  14. $this->db->rollback();
  15. return;
  16. }
  17. $robotPart = new RobotParts();
  18. $robotPart->robots_id = $robot->id;
  19. $robotPart->type = 'head';
  20. // The model failed to save, so rollback the transaction
  21. if ($robotPart->save() === false) {
  22. $this->db->rollback();
  23. return;
  24. }
  25. // Commit the transaction
  26. $this->db->commit();
  27. }
  28. }

Implicit Transactions

Existing relationships can be used to store records and their related instances, this kind of operation implicitly creates a transaction to ensure that data is correctly stored:

  1. <?php
  2. $robotPart = new RobotParts();
  3. $robotPart->type = 'head';
  4. $robot = new Robots();
  5. $robot->name = 'WALL-E';
  6. $robot->created_at = date('Y-m-d');
  7. $robot->robotPart = $robotPart;
  8. // Creates an implicit transaction to store both records
  9. $robot->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. This kind of transaction requires a transaction manager that globally manages each transaction created ensuring that they are correctly rolled back/committed before ending the request:

  1. <?php
  2. use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
  3. use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
  4. try {
  5. // Create a transaction manager
  6. $manager = new TxManager();
  7. // Request a transaction
  8. $transaction = $manager->get();
  9. $robot = new Robots();
  10. $robot->setTransaction($transaction);
  11. $robot->name = 'WALL·E';
  12. $robot->created_at = date('Y-m-d');
  13. if ($robot->save() === false) {
  14. $transaction->rollback(
  15. 'Cannot save robot'
  16. );
  17. }
  18. $robotPart = new RobotParts();
  19. $robotPart->setTransaction($transaction);
  20. $robotPart->robots_id = $robot->id;
  21. $robotPart->type = 'head';
  22. if ($robotPart->save() === false) {
  23. $transaction->rollback(
  24. 'Cannot save robot part'
  25. );
  26. }
  27. // Everything's gone fine, let's commit the transaction
  28. $transaction->commit();
  29. } catch (TxFailed $e) {
  30. echo 'Failed, reason: ', $e->getMessage();
  31. }

Transactions can be used to delete many records in a consistent way:

  1. <?php
  2. use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
  3. use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
  4. try {
  5. // Create a transaction manager
  6. $manager = new TxManager();
  7. // Request a transaction
  8. $transaction = $manager->get();
  9. // Get the robots to be deleted
  10. $robots = Robots::find(
  11. "type = 'mechanical'"
  12. );
  13. foreach ($robots as $robot) {
  14. $robot->setTransaction($transaction);
  15. // Something's gone wrong, we should rollback the transaction
  16. if ($robot->delete() === false) {
  17. $messages = $robot->getMessages();
  18. foreach ($messages as $message) {
  19. $transaction->rollback(
  20. $message->getMessage()
  21. );
  22. }
  23. }
  24. }
  25. // Everything's gone fine, let's commit the transaction
  26. $transaction->commit();
  27. echo 'Robots were deleted successfully!';
  28. } catch (TxFailed $e) {
  29. echo 'Failed, reason: ', $e->getMessage();
  30. }

Transactions are reused no matter where the transaction object is retrieved. A new transaction is generated only when a commit() or :code:rollback() is performed. You can use the service container to create the global transaction manager for the entire application:

  1. <?php
  2. use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager;
  3. $di->setShared(
  4. 'transactions',
  5. function () {
  6. return new TransactionManager();
  7. }
  8. );

Then access it from a controller or view:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class ProductsController extends Controller
  4. {
  5. public function saveAction()
  6. {
  7. // Obtain the TransactionsManager from the services container
  8. $manager = $this->di->getTransactions();
  9. // Or
  10. $manager = $this->transactions;
  11. // Request a transaction
  12. $transaction = $manager->get();
  13. // ...
  14. }
  15. }

While a transaction is active, the transaction manager will always return the same transaction across the application.