Created
May 8, 2012 04:21
-
-
Save vbugarsk/2632543 to your computer and use it in GitHub Desktop.
Easy facebook component
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 | |
#Facebook component | |
class FBCore extends CApplicationComponent { | |
//we want to use setters and getter for the public vars. | |
protected $_appId; | |
protected $_appSecret; | |
//this won't be set via config properties! | |
protected $_facebook; | |
public function init() | |
{ | |
parent::init(); | |
} | |
// this can be called the Facebook singleton :) | |
// it will instantiate the facebook original lib and return a reference to it. | |
public function getFacebook() | |
{ | |
if($this->_facebook!==null) | |
return $this->_facebook; | |
Yii::import('path.to.the.PHPSDK.Facebook'); | |
$this->_facebook=new Facebook(array( | |
'appId'=>$this->getAppId(), | |
'secret'=>$this->getAppSecret(), | |
)); | |
return $this->_facebook; | |
} | |
// this will be called right at component initialization, | |
// thus making $this->_appId available in the component. | |
public function setAppId($str) | |
{ | |
$this->_appId=$str; | |
} | |
public function getAppId() | |
{ | |
return $this->_appId; | |
} | |
public function setAppSecret($str) | |
{ | |
$this->_appSecret=$str; | |
} | |
public function getAppSecret() | |
{ | |
return $this->_appSecret; | |
} | |
// now, as far as i know the original facebook library has some nice methods, so why write them here again ? | |
// instead, let's make use of PHP's __call function and call those methods | |
// basically, this is like a class inheritance(class FBCore extends Facebook) | |
// note, __call() will be called only if a requested method doesn't exists in this component class. | |
public function __call($method, $args) | |
{ | |
$facebook=$this->getFacebook(); | |
// if the method exists in the fb class, call it, otherwise let PHP handle the error. | |
if(method_exists($facebook, $method)) | |
{ | |
return call_user_func_array(array($facebook, $method), $args); | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With the above implementation, you can use FB like:
Yii::app()->fbcore->getUser();
// in this case, __call will be called because your component does not have a method called getUser() but facebook class does.
Yii::app()->fbcore->facebook->getUser();
// in this case you access the fb lib directly, thus __call won't be called.