Last active
November 17, 2017 08:34
-
-
Save NtimYeboah/8ac3885ca53abff5c63f7a13dd77645d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class RequestClient | |
{ | |
private $curl; | |
private $baseUrl = env('BASE_URL'); | |
public function __construct() | |
{ | |
$this->curl = curl_init(); | |
} | |
public function makeRequest($path, $method = 'GET', $payload = null, $headers = []) | |
{ | |
$url = $this->baseUrl . $path; | |
$this->setOptions($url, $method, $headers); | |
if ($payload) { | |
$this->buildQuery($payload); | |
} | |
try { | |
$this->execute(); | |
} catch (Exception $e) { | |
// Handle exception | |
} | |
} | |
private function setOptions($url, $method, $headers) | |
{ | |
curl_setopt($this->curl, CURLOPT_URL, $url); | |
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); | |
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 0); | |
curl_setopt($this->curl, CURLOPT_TIMEOUT, 5000); | |
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers); | |
if ($method === 'POST') { | |
curl_setopt($this->curl, CURLOPT_POST, 1); | |
} | |
if ($method === 'PUT'){ | |
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, "PUT"); | |
} | |
} | |
private function buildQuery($payload) | |
{ | |
curl_setopt($this->curl, CURLOPT_POSTFIELDS, http_build_query($payload)); | |
} | |
private function execute() | |
{ | |
$response = curl_exec($this->curl); | |
curl_close($this->curl); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment