I’ve not had to do much recently with Facebook APIs, which I found to be pretty poor a few years ago. However with some projects coming up which will need FB integration and the announcement this week that lots of things are changing, I thought it might be worth getting myself up to date and seeing if anything has improved.
To be fair, today’s PHP SDK looks to be miles ahead of what they were providing in 2011. But for all that the introduction of proper API versioning seems like a positive step, it doesn’t look like they waited to get the docs finished before announcing these changes! I found some PHP SDK documentation links broken (e.g. to the fundamental GraphObject
!), and several features are only documented for PHP if you look at deprecated versions, which have a completely different instantiation style.
So on to my first post here! It’s not a very hard problem but it took me a little while to figure out how to list a user’s friends the ‘new way’.
Show me the code
Let’s assume you already have a FacebookSession called $fbSession
, as that part is fairly well documented for the latest SDK. To get your authenticated user’s friends’ names in an array $this->_friends
(keyed on user ID), you’d do:
$friends = (new FacebookRequest($fbSession, 'GET', '/me/friends'))
->execute()
->getGraphObject(GraphUser::className())
->asArray();
foreach($friends['data'] as $friend) {
$this->_friends[$friend->id] = $friend->name;
}
This is working for me with v4.0.0 of the PHP SDK and the v2.0 API. I explicitly specified the API version in my FacebookRequest
instantiation (not shown), but new apps should default to v2.0 anyway.
Since I didn’t find docs which even explained that I should look at ['data']
(I got to this through printing objects and trial & error), I’m unclear whether it’s possible to get actual objects for the friends listed and examine further properties. Given the new focus on privacy, with app-scoped user IDs and user-controlled sharing settings for each app, I suspect this may be all you get – but any comments would be helpful.
Where are your friends tonight?
Finally, don’t be surprised when your friend list is a bit shorter than before! The new API only returns friends who are also using your app. Perhaps a headache for some developers but I think a positive step for users concerned about data mining and which pieces of their information are being connected by marketers.
A cynic could argue it’s primarily an opportunity for Facebook to become the only ones who can connect those dots and to make more cash in the process – but I’d still rather have it this way than trust every single app to treat everyone’s data responsibly.