/
index.php
133 lines (121 loc) · 3.08 KB
/
index.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<?php
require 'vendor/autoload.php';
include 'vendor/notorm/notorm/NotORM.php';
$dsn = 'sqlite:' . realpath('./data/db.sqlite');
$db = new NotORM(new PDO($dsn));
use Respect\Rest\Router;
$r3 = new Router;
$r3->get('/', function() {
echo '<h1>Hello Respect World</h1>';
});
$r3->get('/hello', function() {
return 'Hello from Path';
});
$r3->get('/users/*', function($screenName) {
echo "User {$screenName}";
});
$r3->get('/users/*/lists/*', function($user, $list) {
return "List {$list} from user {$user}.";
});
$r3->get('/posts/*/*/*', function($year,$month=null,$day=null) {
//list posts, month and day are optional
});
$r3->get('/books', function() use ($db) {
$books = array();
foreach ($db->books() as $book) {
$books[] = array(
'id' => $book['id'],
'title' => $book['title'],
'author' => $book['author'],
'summary' => $book['summary'],
);
}
return $books;
})->accept(
array(
'application/json' => 'json_encode',
)
);
$r3->get('/book/*', function($id) use ($db) {
$book = $db->books()->where('id', $id);
if ($data = $book->fetch()) {
return array(
'id' => $data['id'],
'title' => $data['title'],
'author' => $data['author'],
'summary' => $data['summary'],
);
} else {
return array(
'status' => false,
'message' => sprintf(
'Book ID %s does not exist',
$id
),
);
}
})->accept(
array(
'application/json' => 'json_encode',
)
);
$r3->post('/book', function() use ($db) {
$book = array(
'title' => $_POST['title'],
'author' => $_POST['author'],
'summary' => $_POST['summary'],
);
$result = $db->books->insert($book);
return array(
'id' => $result['id'],
);
})->accept(
array(
'application/json' => 'json_encode',
)
);
$r3->put('/book/*', function($id) use ($db) {
$book = $db->books()->where('id', $id);
if ($book->fetch()) {
parse_str(file_get_contents('php://input'), $put);
$result = $book->update($put);
return array(
'status' => (bool)$result,
'message' => 'Book updated successfully'
);
} else {
return array(
'status' => false,
'message' => sprintf(
'Book id %s does not exist',
$id
),
);
}
})->accept(
array(
'application/json' => 'json_encode',
)
);
$r3->delete('/book/*', function($id) use ($db) {
$book = $db->books()->where('id', $id);
if ($book->fetch()) {
$result = $book->delete();
return array(
'status' => true,
'message' => 'Book deleted successfully',
);
} else {
return array(
'status' => false,
'message' => sprintf(
'Book id %s does not exist',
$id
),
);
}
})->accept(
array(
'application/json' => 'json_encode',
)
);