29
29
composer require chriskacerguis/codeigniter-restserver
30
30
```
31
31
32
+ Note that you will need to copy ` rest.php ` to your ` config ` directory (e.g. ` application/config ` )
33
+
32
34
Step 1: Add this to your controller (should be before any of your code)
33
35
34
36
``` php
@@ -43,15 +45,18 @@ class Example extends RestController
43
45
44
46
## Basic GET example
45
47
46
- Here is a basic example of
48
+ Here is a basic example. This controller, which should be saved as ` Api.php ` , can be called in two ways:
49
+
50
+ * ` http://domain/api/users/ ` will return the list of all users
51
+ * ` http://domain/api/users/id/1 ` will only return information about the user with id = 1
47
52
48
53
``` php
49
54
<?php
50
55
defined('BASEPATH') OR exit('No direct script access allowed');
51
56
52
57
use chriskacerguis\RestServer\RestController;
53
58
54
- class Example extends REST_Controller {
59
+ class Api extends RestController {
55
60
56
61
function __construct()
57
62
{
@@ -63,29 +68,43 @@ class Example extends REST_Controller {
63
68
{
64
69
// Users from a data store e.g. database
65
70
$users = [
66
- ['id' =>
1 , 'name' => 'John', 'email' => '
[email protected] '],
67
- ['id' =>
2 , 'name' => 'Jim', 'email' => '
[email protected] '],
71
+ ['id' =>
0 , 'name' => 'John', 'email' => '
[email protected] '],
72
+ ['id' =>
1 , 'name' => 'Jim', 'email' => '
[email protected] '],
68
73
];
69
74
70
- $id = $this->get('id');
75
+ $id = $this->get( 'id' );
71
76
72
- if ($id === null)
77
+ if ( $id === null )
73
78
{
74
79
// Check if the users data store contains users
75
- if ($users)
80
+ if ( $users )
76
81
{
77
82
// Set the response and exit
78
- $this->response($users, 200);
83
+ $this->response( $users, 200 );
79
84
}
80
85
else
81
86
{
82
87
// Set the response and exit
83
- $this->response([
88
+ $this->response( [
84
89
'status' => false,
85
90
'message' => 'No users were found'
86
- ], 404);
91
+ ], 404 );
92
+ }
93
+ }
94
+ else
95
+ {
96
+ if ( array_key_exists( $id, $users ) )
97
+ {
98
+ $this->response( $users[$id], 200 );
99
+ }
100
+ else
101
+ {
102
+ $this->response( [
103
+ 'status' => false,
104
+ 'message' => 'No such user found'
105
+ ], 404 );
87
106
}
88
107
}
89
108
}
90
109
}
91
- ```
110
+ ```
0 commit comments