Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Transaction.php
Go to the documentation of this file.
1 <?php
8 namespace Magento\Framework\DB;
9 
14 {
20  protected $_objects = [];
21 
27  protected $_objectsByAlias = [];
28 
34  protected $_beforeCommitCallbacks = [];
35 
41  protected function _startTransaction()
42  {
43  foreach ($this->_objects as $object) {
44  $object->getResource()->beginTransaction();
45  }
46  return $this;
47  }
48 
54  protected function _commitTransaction()
55  {
56  foreach ($this->_objects as $object) {
57  $object->getResource()->commit();
58  }
59  return $this;
60  }
61 
67  protected function _rollbackTransaction()
68  {
69  foreach ($this->_objects as $object) {
70  $object->getResource()->rollBack();
71  }
72  return $this;
73  }
74 
80  protected function _runCallbacks()
81  {
82  foreach ($this->_beforeCommitCallbacks as $callback) {
83  call_user_func($callback);
84  }
85  return $this;
86  }
87 
95  public function addObject(\Magento\Framework\Model\AbstractModel $object, $alias = '')
96  {
97  $this->_objects[] = $object;
98  if (!empty($alias)) {
99  $this->_objectsByAlias[$alias] = $object;
100  }
101  return $this;
102  }
103 
110  public function addCommitCallback($callback)
111  {
112  $this->_beforeCommitCallbacks[] = $callback;
113  return $this;
114  }
115 
122  public function save()
123  {
124  $this->_startTransaction();
125  $error = false;
126 
127  try {
128  foreach ($this->_objects as $object) {
129  $object->save();
130  }
131  } catch (\Exception $e) {
132  $error = $e;
133  }
134 
135  if ($error === false) {
136  try {
137  $this->_runCallbacks();
138  } catch (\Exception $e) {
139  $error = $e;
140  }
141  }
142 
143  if ($error) {
144  $this->_rollbackTransaction();
145  throw $error;
146  } else {
147  $this->_commitTransaction();
148  }
149 
150  return $this;
151  }
152 
159  public function delete()
160  {
161  $this->_startTransaction();
162  $error = false;
163 
164  try {
165  foreach ($this->_objects as $object) {
166  $object->delete();
167  }
168  } catch (\Exception $e) {
169  $error = $e;
170  }
171 
172  if ($error === false) {
173  try {
174  $this->_runCallbacks();
175  } catch (\Exception $e) {
176  $error = $e;
177  }
178  }
179 
180  if ($error) {
181  $this->_rollbackTransaction();
182  throw $error;
183  } else {
184  $this->_commitTransaction();
185  }
186  return $this;
187  }
188 }
if(!trim($html)) $alias
Definition: details.phtml:20
addObject(\Magento\Framework\Model\AbstractModel $object, $alias='')
Definition: Transaction.php:95