Section: Developing a REST controller
« Using the CRUD controller | ^ How to develop a module |
− Table of content
REST principles consist of using HTTP protocol features to access and manipulate a ressource. It is true that POST and GET method are very-well known HTTP requests but HTTP also defines PUT and DELETE methods. Thus RESTful says a ressource should be identified by a unique URI and the four HTTP methods should be used to create, modify, delete and display it.
See RESTful on wikipedia.
Now, let's dive into RESTful with Jelix
Controller ¶
As said before, the four HTTP methods are: GET, POST, DELETE, PUT. Each should be implemented in a RESTful controller.
You have to create a new controller implementing jIRestController interface. You won't be able to add actions to it other than the four defined by jIRestController:
class exempleCtrl extends jController implements jIRestController {
function get(){
}
function post(){
}
function put(){
}
function delete(){
}
}
The code of those methods is similar to those of classic actions but you should respect their meaning:
- GET is used to display a ressource
- POST is used to modify a ressource
- PUT is used to create a ressource
- DELETE is used to delete a ressource
Note: implementing jIRestController interface is mandatory to do RESTful. Jelix knows you are doing RESTful by the means of this interface and modify its internal behaviour.
Client request ¶
As said above, there is a unique URI identifying a ressource and only HTTP methods indicates which action of your controller Jelix should execute.
Therefore, if you want to retrieve a REST controller url you shall not indicate an action and leave this field empty in your selector.
Example: with the exemple controller above, its url selector should be "module~exemple:". Note the last ":" character.
With the url result of jUrl::get("module~exemple:"), you will then be able to call it via xmlHttpRequest in a JS script for example. You just have to tell xmlHttpRequest which http method to use (GET, POST, DELETE or PUT).
Note ¶
There is another way to do REST in a classic controller. Scan $_SERVER['REQUEST_METHOD'] value. But this is less a "sexy" solution than a jIRestController interface. ;-)