· 5 years ago · May 10, 2020, 05:02 PM
1// FILE: app/Config/routes.php
2Router::connect('/api/users', array('controller' => 'pages', 'action' => 'getUsers', '[method]' => 'GET'));
3
4// FILE: app/Controller/PagesController.php
5
6 /*
7 * sample url: /api/users?page=1&order=desc&order_by=name&search_by=name&search_value=Sỹ%20An%20Nguyễn
8 * các query string trên là không bắt buộc phải có trong url do trong code có đặt giá trị default
9 */
10 public function getUsers()
11 {
12 // cách truy cập query string trên url
13 // https://book.cakephp.org/2/en/controllers/request-response.html#accessing-querystring-parameters
14 // không có page thì $this->request->query['page'] = null, trả về default $page = 1
15 $page = $this->request->query['page'] ?? 1;
16 $order = $this->request->query['order'] ?? 'asc';
17 $orderBy = $this->request->query['order_by'] ?? 'id';
18
19 // sử dụng component Pagination có sẵn để phân trang
20 // https://book.cakephp.org/2/en/core-libraries/components/pagination.html#pagination
21 $this->Paginator->settings = array(
22 'fields' => ['id', 'name', 'email', 'created_at'], // danh sách trường muốn lấy ra, nếu có JOIN thì nên chỉ định rõ User.id, User.name, ...
23 'limit' => 10, // số bản ghi trên mỗi trang
24 'order' => [
25 "User.$orderBy" => $order // default: 'User.id' => 'asc'
26 ],
27 'page' => $page
28 );
29 // điều kiện tìm kiếm (nếu có)
30 $conditions = [];
31 // ví dụ trường hợp đơn giản nhất là chỉ tìm kiếm theo 1 trường, tìm giá trị bằng chính xác
32 $searchField = $this->request->query['search_by'] ?? null;
33 $searchValue = $this->request->query['search_value'] ?? null;
34 if (isset($searchField) && isset($searchValue)) {
35 $conditions["User.$searchField"] = $searchValue;
36 }
37
38 // lấy dữ liệu
39 try {
40 $data = $this->Paginator->paginate('User', $conditions);
41
42 // data trước chuyển đổi có dạng
43// array(
44// 0 => array(
45// 'User' => array(
46// 'id' => '2392',
47// 'name' => 'Sỹ An Nguyễn',
48// 'email' => 'syan224@gmail.com',
49// 'created_at' => '2019-12-03 12:21:05'
50// )
51// )
52// )
53
54 // lọc key 'User' khỏi kết quả để làm gọn kết quả
55 $data = array_map(function ($item) {
56 return $item['User'];
57 }, $data);
58 // data sau khi lọc bớt key 'User'
59// array(
60// 0 => array(
61// 'id' => '2392',
62// 'name' => 'Sỹ An Nguyễn',
63// 'email' => 'syan224@gmail.com',
64// 'created_at' => '2019-12-03 12:21:05'
65// )
66// )
67 } catch (NotFoundException $exception) {
68 // trường hợp không tìm thấy bản ghi phù hợp kết quả search thì
69 // Pagination sẽ trả về lỗi NotFoundException nên cần catch để quy nó về mẩng rỗng
70 // hoặc có tìm thấy bản ghi, nhưng tham số page lớn hơn tổng số page có được từ số kết quả thì cũng bị NotFoundException
71 $data = [];
72 }
73
74 // render kết quả cho api dưới dạng json
75 $this->autoRender = false;
76 $this->response->type('application/json');
77 $this->response->body(json_encode([
78 'code' => 200,
79 'message' => 'success',
80 'data' => $data
81 ]));
82 return $this->response->send();
83 }