PHP SDK Demystified – The most Frequently Called api() Function!

If someone asks you

What is the most frequently called function in the PHP SDK?

what will be your answer?

For me, the answer is definitely,

the api() method

This is the method that we use for sending out our requests to Facebook server and get the data back.

Before looking at the source code of the PHP SDK, let’s see some typical use of this method.

Sample code is listed below:

// query the "/me" object (i.e. the currently logged in user) vai Graph API
$fbme = $facebook->api('/me');

// query the currenly logged in user's friends via Graph API
$friends = $facebook->api('/me/friends');

// query the currenly logged in user's friends via calling the old REST API's
// friends.get method
$old_rest_call_param = array('method' => 'friends.get');
$friends_old_rest = $facebook->api($old_rest_call_param);

As seen in the above code, we can see that the PHP SDK supports calling both the Old REST API and the Graph API.  (You can also use FQL via the PHP SDK.. which I would say is just calling the “fql.query” Old REST API method.)

Let’s take a look at how the api() method is defined in the PHP SDK:

   * Make an API call.
   * @param Array $params the API call parameters
   * @return the decoded response
  public function api(/* polymorphic */) {
    $args = func_get_args();
    if (is_array($args[0])) {
      return $this->_restserver($args[0]);
    } else {
      return call_user_func_array(array($this, '_graph'), $args);

The api() method will,

  • call the protected function _restserver() if the first parameter passed (i.e. $args[0]) is an array.
    This is for sending out Old REST API requests.
  • otherwise, call the protected function _graph()
    This is for sending out Graph API requests.

After knowing how the PHP SDK determine whether you are calling the Old REST API or the Graph API, I hope you can understand when we need to prepare an array containing the Old REST API method name as the parameter when calling the Old REST API.

In the next article(s), we will take a closer look at how the PHP SDK format the Old REST API request and Graph API request.

This entry was posted in PHP SDK Demystified and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *