Placeholder Image

ADN Informatique

Consultant Ingénierie Informatique

Saguenay (Jonquière), Québec, Canada. Tél: (581) 683-9887 Téléc: (581) 221-0874

Placeholder Picture

Retour

PHP Rest

2008-01-22 14:48:10 (ID: 34, Parent: 33, Type: page)
Utilisation de PHP pour le développement de client et serveurs REST

Les modèles de données et autres informations intéressantes concernant REST

REST utilise les standards mais n'en est pas un http://www.xfront.com/REST-Web-Services.html
REST Data format confusion http://www.peej.co.uk/articles/rest-data-formats.html
Interview imaginaire décrivant les avantages de REST http://duncan-cragg.org/blog/post/getting-data-rest-dialogues/
HTTP 1.1 RFC
Definition de REST sur Wikipedia


Utilisation de Zend Framework

ZendRestClient et ZendRestServer

Utilisation de PEAR HTTP_Request

Voici un exemple de classe "client rest" basé sur PEAR HTTP_Request:
require_once "HTTP/Request.php";
class RESTClient {
private $root_url = "";
private $curr_url = "";
private $user_name = "";
private $password = "";
private $response = "";
private $responseBody = "";
private $req = null;

public function __construct($root_url = "", $user_name = "", $password = "") {
$this->root_url = $this->curr_url = $root_url;
$this->user_name = $user_name;
$this->password = $password;
if ($root_url != "") {
$this->createRequest("GET");
$this->sendRequest();
}
return true;
}

public function createRequest($url, $method, $arr = null) {
$this->curr_url = $url;
$this->req =& new HTTP_Request($url);
if ($this->user_name != "" && $this->password != "") {
$this->req->setBasicAuth($this->user_name, $this->password);
}

switch($method) {
case "GET":
$this->req->setMethod(HTTP_REQUEST_METHOD_GET);
break;
case "POST":
$this->req->setMethod(HTTP_REQUEST_METHOD_POST);
$this->addPostData($arr);
break;
case "PUT":
$this->req->setMethod(HTTP_REQUEST_METHOD_PUT);
// to-do
break;
case "DELETE":
$this->req->setMethod(HTTP_REQUEST_METHOD_DELETE);
// to-do
break;
}
}

private function addPostData($arr) {
if ($arr != null) {
foreach ($arr as $key => $value) {
$this->req->addPostData($key, $value);
}
}
}

public function sendRequest() {
$this->response = $this->req->sendRequest();

if (PEAR::isError($this->response)) {
echo $this->response->getMessage();
die();
} else {
$this->responseBody = $this->req->getResponseBody();
}
}

public function getResponse() {
return $this->responseBody;
}
}
Son utilisation est très simple, en voici un exemple:

require_once "RESTclient.php";
$rest = new RESTclient();
$inputs = array();
$inputs["appid"] = "YahooDemo";
$inputs["street"] = "701 First Street";
$inputs["city"] = "Sunnyvale";
$inputs["state"] = "CA";
$url = "http://api.local.yahoo.com/MapsService/V1/geocode/"
$rest->createRequest("$url","POST",$inputs);
$rest->sendRequest();
$output = $rest->getResponse();
echo $output;

Document Informatif

ADN Informatique

2015

Rev. 1

Jean-Luc Cyr