CodeIgniter – REST

CodeIgniter – REST

CodeIgniter – REST

CodeIgniter – REST

Author : Damiano Venturin
Download : Direct Download
Sort Description : CodeIgniter – REST merupakan sebuah paket CodeIgniter yang telah ditambah dan terkonfigurasi REST API. Dimana kita melanjutkan untuk membangun aplikasi yang kita ingin buat.
Type : Web tools, CI addons
Status : FREE
 

More Info


Cara menginstal tinggal copas hasil downloadadn paket CodeIgniter – REST, lalu mulai coding sesuai coding dengan CI biasa…

Ingat : cURL harus sudah di enable , cara enable cURL tinggal uncomment pada file php.ini di server anda…

link referensi :
Saprk untuk CI
referensi cara make rest

 

Contoh Code server rest


Di bawah ini contoh rest server menggunakan model barang, kalo ada yang bingun tinggal komen di bawah aja… ok?

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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
<?php defined('BASEPATH') OR exit('No direct script access allowed');
 
/**
 * Example
 *
 * This is an example of a few basic user interaction methods you could use
 * all done with a hardcoded array.
 *
 * @package		CodeIgniter
 * @subpackage          Rest Server
 * @category            Controller
 * @author		WisPukako
 * @link		http://www.pukakomedia.net/
*/
 
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH.'/libraries/REST_Controller.php';
 
class Rest_Barang extends REST_Controller
{
	protected $builtInMethods;
 
	public function __construct()
	{
		parent::__construct();
		$this->__getMyMethods();
                $this->load->model('m_barang');
	}
 
	/**
	 *
	 * Analizes self methods using reflection
	 * @return Boolean
	 */
	private function __getMyMethods()
	{
		$reflection = new ReflectionClass($this);
 
		//get all methods
		$methods = $reflection->getMethods();
		$this->builtInMethods = array();
 
		//get properties for each method
		if(!empty($methods))
		{
			foreach ($methods as $method) {
				if(!empty($method->name))
				{
					$methodProp = new ReflectionMethod($this, $method->name);
 
					//saves all methods names found
					//$this->builtInMethods['all'][] = $method->name;
 
					//saves all private methods names found
					if($methodProp->isPrivate())
					{
						//$this->builtInMethods['private'][] = $method->name;
					}
 
					//saves all private methods names found
					if($methodProp->isPublic())
					{
						$this->builtInMethods['public'][] = $method->name;
 
						// gets info about the method and saves them. These info will be used for the xmlrpc server configuration.
						// (only for public methods => avoids also all the public methods starting with '_')
						if(!preg_match('/^_/', $method->name, $matches))
						{
							//consider only the methods having "_" inside their name
							if(preg_match('/_/', $method->name, $matches))
							{
								//don't consider the methods get_instance and validation_errors
								if($method->name != 'get_instance' AND $method->name != 'validation_errors')
								{
									// -method name: user_get becomes [GET] user
									$name_split = explode("_", $method->name);
									$this->builtInMethods['functions'][$method->name]['function'] = $name_split['0'].' [method: '.$name_split['1'].']';
 
									// -method DocString
									$this->builtInMethods['functions'][$method->name]['docstring'] =  $this->__extractDocString($methodProp->getDocComment());
								}
							}
						}
					}
				}
			}
		} else {
			return false;
		}
		return true;
	}
 
        /* ==========================================================================================
	 * Manipulates a DocString and returns a readable string
	 * @param String $DocComment
	 * @return Array $_tmp
	 */
	private function __extractDocString($DocComment)
	{
		$split = preg_split("/\r\n|\n|\r/", $DocComment);
		$_tmp = array();
		foreach ($split as $id => $row)
		{
			//clean up: removes useless chars like new-lines, tabs and *
			$_tmp[] = trim($row, "* /\n\t\r");
		}
		return trim(implode("\n",$_tmp));
	}
 
        /* ==========================================================================================
         * API : return all of API available in this class
         * ==========================================================================================
         */
        public function API_get()
	{
		$this->response($this->builtInMethods, 200); // 200 being the HTTP response code
	}
 
        /* ==========================================================================================
         * name     : barangsatu_get = mengambil informasi satu barang berdasarkan id
         * by       :
         * how to   :
         *  -- call function : `barangsatu/id/{id of barang}/format/{json/xml/*}
         *  -- variable : id = id dari barang yang akan dicari
         *  -- output : mengambelikan semua atribut dari barang sesuai dengan format yang diminta
         */
        function a_barang_get()
        {
            /*
             * check apakah atribut id sudah di set saat pemanggilan
             */
            if(!$this->get('id'))
            {
                    $this->response(NULL, 400);  // jika belom diset maka akan dibawa ke page not found
            }
            /*
             * jika sudah diset
             */
            else {
                /*
                 * mengambil data sesuai dengan id
                 */
                $query = $this->m_barang->get_barang_by($this->get('id'));
 
                /*
                 * jika query berhasi akan ditampilkan hasilnya
                 */
                if($query) {
                    $this->response($query, 200); // 200 being the HTTP response code
                }
 
                else {
                    $this->response(array('error' => 'User could not be found'), 404);
                }
            }
        }
 
        /* ==========================================================================================
         * name     : all_barang_get : mengambil semua informasi barang secara lengkap
         * by       :
         * how to   :
         *  -- call function : /all_barang/format/{json/xml/*}
         *  -- variable : -
         *  -- output : mengambelikan semua atribut dari barang sesuai dengan format yang diminta
         */
         function all_barang_get()
         {
             /*
              * query semu data barang dari database
              */
            $query = $this->m_barang->get_all_barang();
 
            /*
             * jika query berhasil
             */
            if($query)
            {
                $this->response($query, 200); // 200 being the HTTP response code
            }
 
            else
            {
                $this->response(array('error' => 'User could not be found'), 404);
            }
        }
}
?>
 

Contoh Code client rest


untuk memanggil fungsi yang disediakan server cukup mudah tingga lihat contoh dibawah ini… klo ada bingung komen aja ya…

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
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Created on Aug 26, 2011 by Damiano Venturin @ Squadra Informatica
 
class Rest_Client extends CI_Controller {
	public function __construct() 
	{
		parent::__construct();
 
		// Load the configuration file
		$this->load->config('rest');
 
		// Load the rest client
		$this->load->spark('restclient/2.0.0');		
		$this->rest->initialize(array('server' => $this->config->item('rest_server')));
		//$this->rest->initialize(array('server' => 'http://localhost/codeigniter-rest-example/index.php/rest_server/'));
	}
 
	public function index()
	{
		$data['methods_list'] = $this->displayAPI();
		$this->load->view('restDoc',$data);				
	}
 
	/**
	 * 
	 * Produces a human readable list of methods available on the server side
	 */
	public function displayAPI()
	{
		//get methods list
        $methods_html = '';
        $methods = (array) $this->rest->get('API/format/json');
 
        //show the docstring for the method
        if(count($methods['functions'])>0)
        {
        	foreach ( $methods['functions'] as  $method) {	    
				if(empty($method->docstring))
				{
					$methods_html .= '<dt>'.$method->function.'</dt><dd>No description available</dd>';
				} else {
					$methods_html .= '<dt>'.$method->function.'</dt><dd>'.$method->docstring.'</dd>';
				}
        	}	
        	$methods_html .= '</dl>';
        }
 
//		echo '<pre>';
//		print_r($methods);
//		echo '</pre>';         
 
       	return $methods_html;				
	}		
 
	/**
	 * 
	 * Access API "Barang" dari server rest
	 */
	public function getAllBarang()
	{
		echo '<pre>';
		print_r($this->rest->get('all_barang/format/json'));
		echo '</pre>';
	}
}
?>
 
 

Share this post