用于CodeIgniter的一個完整RESTful服務器實現:CodeIgniter Rest Server

jopen 9年前發布 | 43K 次閱讀 CodeIgniter Web框架 CodeIgniter Rest Server

用于CodeIgniter的一個完整RESTful服務器實現,只用到一個庫,一個配置文件和一個控制器。

Requirements

  1. PHP 5.4 or greater
  2. CodeIgniter 3.0+

Note: for 1.7.x support download v2.2 from Downloads tab

Installation

Drag and drop the application/libraries/Format.php and application/libraries/REST_Controller.php files into your application's directories. To userequire_onceit at the top of your controllers to load it into the scope. Additionally, copy the rest.php file from application/config in your application's configuration directory.

Handling Requests

When your controller extends fromREST_Controller, the method names will be appended with the HTTP method used to access the request. If you're making an HTTPGETcall to/books, for instance, it would call aBooks#index_get()method.

This allows you to implement a RESTful interface easily:

class Books extends REST_Controller
{
  public function index_get()
  {
    // Display all books
  }

  public function index_post()
  {
    // Create a new book
  }
}

REST_Controlleralso supportsPUTandDELETEmethods, allowing you to support a truly RESTful interface.

Accessing parameters is also easy. Simply use the name of the HTTP verb as a method:

$this->get('blah'); // GET param
$this->post('blah'); // POST param
$this->put('blah'); // PUT param

The HTTP spec for DELETE requests precludes the use of parameters. For delete requests, you can add items to the URL
public function index_delete($id)
{
    $this->response([
        'returned from delete:' => $id,
    ]);
}

If query parameters are passed via the URL, regardless of whether it's a GET request, can be obtained by the query method:

$this->query('blah'); // Query param

項目主頁:http://www.baiduhome.net/lib/view/home/1442241855618

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!