PHP CodeIgniter加入RESTful功能,實作API網站
來源資料:http://xtony77.logdown.com/posts/247014-notes-php-codeigniter-join-the-restful-function
CodeIgniter的RESTful功能可以用來輸出JSON或XML格式,對此可以提供API給手機APP使用。
套件:codeigniter-restserver
套件:codeigniter-restserver
更正:CodeIgniter的RESTful功能可以拿來做一般網站的CRUD功能,之前誤以為只能產出JSON,其實改用
$this->load->view()一樣可以產出網頁頁面1. 將必要的3個檔案加到CI專案資料夾中。
application/libraries/Format.phpapplication/libraries/REST_Controller.phpapplication/config/rest.php
2. 更改預設輸出格式
在
application/config/rest.php檔案裡面更改預設輸出格式,預設使用XML,而我個人是使用JSON格式。$config['rest_default_format'] = 'json';
3. Controller使用方式
- require
REST_Controller.php檔案 - Controller的class extends
REST_Controller
require(APPPATH.'/libraries/REST_Controller.php');
class {ClassName} extends REST_Controller
{
....
}
4. Controller的function使用方式
- 這邊範例function叫做index,而function後面一定要接這4個其中一個:
_get、_post、_put、_delete - 輸出JSON要呼叫
$this->response,JSON格式就看你的array怎麼寫 - 其他使用方式就跟原本的CodeIgniter操作蕾同,只是不會使用到view。
public function index_get( $params ){
$this->get('params');
$this->post('params');
$this->put('params');
....
$this->response( array );
}
5. 可以配合routes檔使用
編輯
config/routes.php
這個範例是controller後面帶了id,叫做(:any)任何字串,也可以使用(:num)任何數字,然後後面又帶入了一個變數當作功能的辨別,例如id底下的total全部。而導向網址就可以用
$1去接(:any)的值變成get參數。$route['controller/(:any)/total'] = 'controller_total/$1';
情境範例:透過routes設定,就可以分兩個function寫,不用當巢男
// URL:controller/index/id
public function index_get( $id ) {
....
}
// URL:controller/index/id/total
public function index_total_get( $id ) {
...
}
留言
張貼留言