Skip to content

Instantly share code, notes, and snippets.

@c4software
Created December 12, 2013 09:29
Show Gist options
  • Save c4software/7925355 to your computer and use it in GitHub Desktop.
Save c4software/7925355 to your computer and use it in GitHub Desktop.
Librairie d'appel rest
<?php
/**
* Exemples d'utilisations
* $rest = new RestClient("http://10.40.1.9:8080/afone-webcallback-ws/",False);
* $result = $rest->prepare("gestioncommande/terminecommande")->get(array("idcmde"=>666));
* TODO Fair des exemples.
*/
class RestClient {
private $_url;
private $return_header = False;
public function __construct($rest_url="",$return_header=False)
{
$this->return_header = $return_header;
if($rest_url != "")
{
$this->_url = $rest_url;
}
else
{
$this->_url = _rest_host;
}
}
public function prepare($pUrl = "") {
$this->_url .= $pUrl;
return $this;
}
public function get($pParams = array()) {
return $this->_launch($this->_makeUrl($pParams), $this->_createContext('GET'));
}
public function post($pPostParams = array(), $pGetParams = array()) {
return $this->_launch($this->_makeUrl($pGetParams), $this->_createContext('POST', $pPostParams));
}
public function put($pContent = null, $pGetParams = array()) {
return $this->_launch($this->_makeUrl($pGetParams), $this->_createContext('PUT', $pContent));
}
public function delete($pContent = null, $pGetParams = array()) {
return $this->_launch($this->_makeUrl($pGetParams), $this->_createContext('DELETE', $pContent));
}
protected function _createContext($pMethod, $pContent = null) {
$opts = array('http' => array('method' => $pMethod, 'header' => 'Content-type: application/x-www-form-urlencoded', ));
if ($pContent !== null) {
if (is_array($pContent)) {
$pContent = http_build_query($pContent);
}
$opts['http']['content'] = $pContent;
}
return stream_context_create($opts);
}
protected function _makeUrl($pParams) {
return $this->_url . (strpos($this->_url, '?') ? '' : '?') . http_build_query($pParams);
}
protected function _launch($pUrl, $context) {
if (($stream = fopen($pUrl, 'r', false, $context)) !== false) {
$content = stream_get_contents($stream);
$header = stream_get_meta_data($stream);
fclose($stream);
if($this->return_header)
{
return array('content' => $content, 'header' => $header);
}
else
{
return array('content' => $content);
}
} else {
return false;
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment