/
controllers.php
89 lines (77 loc) · 2.13 KB
/
controllers.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
class Controller {
public $flash = array();
private $attributes = array();
public function insert() {
$address = new Address($_POST['name'], $_POST['phone']);
if (AddressBookService::insert($address)) {
$this->addNotice('notice', 'Successfully added new address.');
$this->redirectTo('index');
} else {
$this->addNotice('notice', 'Failed to add new address.');
$this->renderView('index');
}
}
public function edit() {
$address = AddressBookService::find($_GET['id']);
if ($address) {
$this->set('ediable_address', $address);
$this->renderView('index');
} else {
$this->addNotice('notice', 'Failed to edit your content');
$this->redirectTo('index');
}
}
public function remove() {
if (AddressBookService::remove($_GET['id'])) {
$this->addNotice('notice', 'Successfully removed!');
$this->redirectTo('index');
} else {
$this->addNotice('notice', 'Failed to remove');
$this->redirectTo('index');
}
}
public function index() {
$this->set('addresses', AddressBookService::findAll());
$this->renderView('index');
}
protected function set($key, $value) {
$this->attributes[$key] = $value;
return $this;
}
protected function get($key) {
return $this->attributes[$key];
}
protected function addNotice($key, $value) {
$_SESSION['flash' . $key] = $value;
}
protected function getNotice($key) {
if (in_array('flash' . $key, $_SESSION)) {
$notice = $_SESSION['flash' . $key];
if (!empty($notice)) {
unset($_SESSION['flash' . $key]);
}
return $notice;
} else {
return false;
}
}
private function renderView($viewFile) {
include 'views/' . $viewFile . '.html.php';
}
private function redirectTo($pathOrAction) {
if (method_exists($this, $pathOrAction)) {
header('Location: ' . 'index.php?perform=' . $pathOrAction);
} else {
header('Location: ' . $pathOrAction);
}
}
public function dispatch($action = NULL) {
if ($action == NULL || empty($action)) {
$this->index();
} else if (!empty($action)) {
$this->$action();
}
}
}
?>