Skip to content

Instantly share code, notes, and snippets.

@charlycoste
Last active December 24, 2015 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlycoste/6864561 to your computer and use it in GitHub Desktop.
Save charlycoste/6864561 to your computer and use it in GitHub Desktop.
<?php
/**
* @see http://www.croes.org/gerald/blog/ecrire-un-client-rest-en-php-23/490/
*/
class RestClient
{
private $_url;
public function setUrl ($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);
return array('content'=>$content, 'header'=>$header);
}else{
return false;
}
}
}
<?php
$rest = new RestClient();
//lecture d'un livre
$livre = $rest->setUrl('http://bibliotheque/livre/1')->get();
//ecriture d'un livre
$rest->setUrl('http://bibliotheque/livre')->post($unLivre);
//modification d'un livre
$rest->setUrl('http://bibliotheque/livre/1')->put($unLivre);
//supression d'un livre
$rest->setUrl('http://bibliotheque/livre/1')->delete();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment