1: <?php
2:
3: App::uses('UndoableOperation', 'Operations.Lib');
4: App::uses('CommitableOperation', 'Operations.Lib');
5:
6: class ModelOperations {
7:
8: public static function save($model, $data) {
9: return new ModelOperations_Save($model, $data);
10: }
11:
12: public static function delete($model, $id) {
13: return new ModelOperations_Delete($model, $id);
14: }
15:
16: }
17:
18: class ModelOperations_Save implements CommitableOperation {
19:
20: /**
21: *
22: * @var Model
23: */
24: private $model;
25:
26: /**
27: *
28: * @var array
29: */
30: private $data;
31:
32: public function __construct($model, $data) {
33: if (is_string($model)) {
34: $this->model = ClassRegistry::init($model);
35: } else {
36: $this->model = $model;
37: }
38:
39: $this->data = $data;
40: }
41:
42: public function __toString() {
43: return __CLASS__ . "({$this->model->name}/{$this->model->alias} => " . print_r($this->data, true) . ")";
44: }
45:
46: public function commit() {
47: $this->model->commit();
48: }
49:
50: public function run() {
51: $this->model->begin();
52: if (empty($this->data[$this->model->alias][$this->model->primaryKey])) {
53: $this->model->create();
54: }
55: return $this->model->save($this->data);
56: }
57:
58: public function undo() {
59: $this->model->rollback();
60: }
61:
62: }
63:
64: class ModelOperations_Delete implements CommitableOperation {
65:
66: /**
67: *
68: * @var Model
69: */
70: private $model;
71:
72: /**
73: *
74: * @var mixed
75: */
76: private $id;
77:
78: public function __construct($model, $id) {
79: if (is_string($model)) {
80: $this->model = ClassRegistry::init($model);
81: } else {
82: $this->model = $model;
83: }
84:
85: $this->id = $id;
86: }
87:
88: public function __toString() {
89: return __CLASS__ . "({$this->model->name}/{$this->model->alias} => {$this->id})";
90: }
91:
92: public function commit() {
93: $this->model->commit();
94: }
95:
96: public function run() {
97: $this->model->begin();
98: return $this->model->delete($this->id);
99: }
100:
101: public function undo() {
102: $this->model->rollback();
103: }
104:
105: }