1: <?php
2:
3: class TransactionOperation {
4:
5: private $operations = array();
6:
7: public function execute(UndoableOperation $operation) {
8: if (($result = $operation->run())) {
9: $this->operations[] = $operation;
10: return $result;
11: } else {
12: $operation->undo();
13: $this->rollback();
14: throw new Exception("Error on executing \"$operation\"");
15: }
16: }
17:
18: /**
19: * @return void
20: */
21: public function rollback() {
22: while (!empty($this->operations)) {
23: $operation = array_pop($this->operations);
24: try {
25: $operation->undo();
26: } catch (Exception $ex) {
27: //Ignores fail
28: }
29: }
30: }
31:
32: /**
33: * @return void
34: */
35: public function commit() {
36: foreach ($this->operations as $operation) {
37: if ($operation instanceof CommitableOperation) {
38: try {
39: $operation->commit();
40: } catch (Exception $ex) {
41: //Ignores fail
42: }
43: }
44: }
45: }
46:
47: public function __toString() {
48: $b = '';
49: foreach ($this->operations as $operation) {
50: $b .= "$operation\n";
51: }
52: return $b;
53: }
54:
55: }