Created
March 7, 2012 14:26
-
-
Save nikoheikkila/1993437 to your computer and use it in GitHub Desktop.
PHP: cURL Wrapper with traits
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 | |
/** | |
* cURL Wrapper trait for PHP => 5.4 | |
* | |
* Contains several API classes which uses this trait | |
*/ | |
trait curl | |
{ | |
public function curl($url) | |
{ | |
/* Init cURL */ | |
$ch = curl_init(); | |
/* Set options and execute */ | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
$output = curl_exec($ch); | |
/* Close handle and return output */ | |
curl_close($ch) | |
return $output; | |
} | |
} | |
/** | |
* Twitter API class | |
*/ | |
class TwitterAPI | |
{ | |
/* use trait here */ | |
use curl; | |
public function get($url) | |
{ | |
return json_encode($this->curl('https://api.twitter.com/' . $url)); | |
} | |
} | |
/** | |
* Facebook API class | |
*/ | |
class FacebookAPI | |
{ | |
/* use trait here */ | |
use curl; | |
public function get($url) | |
{ | |
return json_encode($this->curl('https://graph.facebook.com/' . $url)); | |
} | |
} | |
/* | |
Example | |
class myAPI | |
{ | |
use curl; | |
public function get($url) | |
{ | |
return json_encode($this->curl('http://api.example.org/' . $url)); | |
} | |
} | |
*/ | |
/* | |
$facebook = new FacebookAPI(); | |
echo $facebook->get('100000753332907') | |
Output: | |
{ | |
"id": "100000753332907", | |
"name": "Niko Heikkil\u00e4", | |
"first_name": "Niko", | |
"last_name": "Heikkil\u00e4", | |
"link": "https://www.facebook.com/nj.heikkila", | |
"username": "nj.heikkila", | |
"gender": "male", | |
"locale": "en_GB" | |
} | |
$twitter = new TwitterAPI(); | |
echo $twitter->get('1/users/show.json?screen_name=nikoheikkila'); | |
Output: long text :-) | |
*/ | |
/** | |
* Fill to your hearts needs | |
* | |
* TIP: You might want to use metaprogramming to create getters automatically | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment