Skip to content

Commit 7962955

Browse files
committed
Re-tweaked example (again)
This should take into consideration many forms
1 parent 4e4afa1 commit 7962955

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

application/controllers/api/Example.php

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ function __construct()
3030
$this->methods['user_delete']['limit'] = 50; // 50 requests per hour per user/key
3131
}
3232

33-
public function users_get($id = NULL)
33+
public function users_get($id_param = NULL)
3434
{
3535
// Users from a data store e.g. database
3636
// $user = $this->some_model->getSomething($id);
@@ -40,8 +40,17 @@ public function users_get($id = NULL)
4040
3 => ['id' => 3, 'name' => 'Jane', 'email' => 'jane@example.com', 'fact' => 'Lives in the USA', ['hobbies' => ['guitar', 'cycling']]],
4141
];
4242

43+
// Get the id parameter value
44+
$id = $this->get('id');
45+
46+
// If NULL, then check the id passed as users/:id
47+
if ($id === NULL)
48+
{
49+
$id = $id_param;
50+
}
51+
4352
// If the id parameter and query parameter don't exist, return all users instead
44-
if ($id === NULL && $this->get('id') === NULL)
53+
if ($id === NULL)
4554
{
4655
// Check if the users data store contains users (in case the database result returns NULL)
4756
if ($users)
@@ -60,16 +69,13 @@ public function users_get($id = NULL)
6069

6170
}
6271

63-
// If the id has not been passed via the URL e.g. example/users/:id, then
64-
// check the id query parameter id=? instead
65-
if ($id === NULL || ctype_digit($id) === FALSE)
72+
// Check if the id is a valid integer
73+
if (ctype_digit($id))
6674
{
67-
$id = $this->get('id');
75+
// Cast as an int
76+
$id = (int) $id;
6877
}
6978

70-
// Cast as an int
71-
$id = (int) $id;
72-
7379
// If not a valid id
7480
if ($id <= 0)
7581
{
@@ -107,17 +113,23 @@ public function users_post()
107113
$this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
108114
}
109115

110-
public function users_delete()
116+
public function users_delete($id_param = NULL)
111117
{
112-
// If the id has not been passed via the URL e.g. example/users/:id, then
113-
// check the id query parameter id=? instead
118+
// Get the id parameter value
119+
$id = $this->get('id');
120+
121+
// If NULL, then check the id passed as users/:id
114122
if ($id === NULL)
115123
{
116-
$id = $this->get('id');
124+
$id = $id_param;
117125
}
118126

119-
// Cast as an int
120-
$id = (int) $id;
127+
// Check if the id is a valid integer
128+
if (ctype_digit($id))
129+
{
130+
// Cast as an int
131+
$id = (int) $id;
132+
}
121133

122134
// If not a valid id
123135
if ($id <= 0)

0 commit comments

Comments
 (0)