Cutting to the chase: There is an API which my application will be using to make calls to, using cURL. However this API needs to be kept secret, so I'm using a framework to create my own API to query the external API. I have done this, but it's really messy and is bad coding - so I want to do this as properly as I can, for my own learning.
I first create my interface:
interface APICall {
/**
* Return data from the API
* @returns json
*/
public function callData($method, $parameters);
}
I then create my class, which will be doing the cURL (will just do a GET request for now):
class curl {
private static $apiUrl = 'http://api.somewebsite.com/v1/';
public function __construct() {
if (!function_exists('curl_init'))
exit('CURL is not installed!');
}
public function getCurl($method, $parameters) {
$url = self::$apiUrl . $method . '?' . $parameters;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
// Another function for a POST request could go here
}
Okay, so now I'd create my classes for each specific call, for example "Get the list of users":
class users extends curl implements APICall {
/**
* Get list of users
*/
public function callData($method, $parameters) {
$this->getCurl($method, $parameters);
}
}
Okay - now I'm not entirely sure this will work (brainstorming for now), but I do feel I'll have some issues:
The
__constructin my curl class, I don't think this should be containing a "check if cURL is installed" check - but where would this best go?I'm building the
$urlwithin each method in the curl class - this just seems bad since I'll end up repeating this - but where do I create that to be used?I feel as if I'm using
$method&$parametersquite frequently, is this normal?
Sorry if this is quite a bit, just trying to understand it as my current coding practices are crap!
exit, though; it should probably be throwing an exception instead.$methodand$parametersthing. Were yourcallDatafunction renamed to__call, the caller would never even have to know the method is dynamic; it can just say$obj->someMethod($params). This makes it pretty easy to build a proxy object representing the underlying API, without making things ugly for the caller.