Mastering Facebook application development with PHP, Rational Application Developer, WebSphere Application Server, and DB2, Part 1: Set up the components

Develop a Facebook application using both PHP and Java™ programming languages. This tutorial gives you a first look at Facebook, and then steps you through the process for installing the components needed to create a Facebook application. Next, you'll take a tour of Facebook with respect to how to integrate your application into the site. Finally, you'll get started with a barebone application. In Parts 2 and 3 of this tutorial series, you'll learn how to develop the application you create in Part 1.


Jake Miles (, Freelance writer, Conde Nast

Author photoJake Miles is a senior developer at Conde Nast, currently working with Facebook, Myspace, and OpenSocial applications, using Java, PHP, Adobe Flex and Javascript. He has been working as a professional developer for 10 years and has been an avid student and tinkerer since he was 10. He also teaches on a volunteer basis, and believes that anyone can learn anything if taught clearly enough.

16 May 2008

Also available in Chinese Vietnamese

Before you start

This tutorial is for developers with at least some experience developing for the Web with PHP, Java language, Javascript, HTML/CSS, and a relational database, who want to step into the emerging world of Facebook application development. You'll learn about Facebook itself, the various integration points it provides for an application, how Facebook and your application communicate with each other, and how to develop useful and interactive behavior using Facebook's API.

About this tutorial

In this tutorial, you will start to build a Facebook application, hypothetically written by an existing stock brokerage firm, that allows a user to manage their portfolio from within Facebook. To make the application truly social, and not just a widget embedded within Facebook, you will also provide the option of treating one's stock portfolio as a competitive game with other users.

Don't have the code?

Download free trial versions of the products used in this tutorial:

To give a more real-world technical scenario, you will assume that part of the application is already written in Java language, and that you're adding the Facebook application and writing it in PHP and Java. You will implement some of the application in Java, using IBM Rational® Application Developer Java authoring environment, WebSphere® as your J2EE application server, and Facebook's Java Client Library for communication between WebSphere and Facebook.

You will also implement some of the application in PHP, using the Zend Core engine and its bundled installation of Apache 2 to serve the pages, and Facebook's PHP Client Library to communicate with Facebook. This will give you hands-on experience with both Java and PHP, so you can better choose between them as the needs of your enterprise change.

System requirements

To complete the steps in this tutorial, you need the following software. If you don't have the products installed, or don't have the latest release, you can download free trial versions:

Introducing Facebook

In this section, you'll take a first look at Facebook before you install the components and explore Facebook application development.

What is Facebook?

Until recently, users remained fairly isolated on the Web. You could interact with servers operating across the globe and find vast amounts of information, but you didn't interact online so much with other human beings. Social networking sites like Facebook -- the current front runner in popularity -- have changed that, allowing users to create online profiles for themselves and easily recreate their existing network of friends online. This creates an entirely new space in which people can interact with each other. Enabling this interaction are social applications; applications embedded within the social network site that each provide their own way to interact with one's friends on the network. Since users are spending more and more time on social sites like Facebook, these sites have the potential to become an operating system of their own.

The two faces of facebook

Facebook is two things: a network of friends, and a platform for components that interact with that network, called applications. Almost all of Facebook's functionality builds off this simple, unified design - most of Facebook's default functions, like the ability to manage your photos and groups, are Facebook applications. Facebook's various APIs also expose much of the base applications' functionality and data, like a user's list of friends and photos, and so provide lots of rich access and support for developing your own applications.

When you first log into your Facebook account you see your home page, as shown in Figure 1.

Figure 1. Your Facebook home page
Your Facebook homepage

The leftmost column contains a search box, navigation links to all your installed applications, and an ad. Along with the top navigation bar, this leftmost column frames all pages that you view within Facebook.

The home page itself is the content next of the navigation column, and is itself divided into two columns. The left column of the home page contains your News Feed, which is a blog of one-line items announcing many of your friends' actions in their applications.

The profile

The home page is what an individual user sees about their network. The user's profile, reached by clicking the Profile link in the header navigation bar, is the user's public-facing page (see Figure 2).

Figure 2. The profile page
The profile page

The Profile page is also divided into two columns (to the right of the Facebook navigation column), which we'll just call the "narrow" and the "wide" column, both of which contain Facebook-installed and user-installed applications. Also of interest to application developers are the list of Profile Actions that appear directly beneath the profile's photo, put there by applications, the set of installed applications' icons that appear beneath that, each of which scrolls the profile page to that application's box, and the Mini-Feed application, which displays a superset of the items displayed in the News Feed.

Now that you've explored the main aspects of Facebook that you need to know, it's time to install all of the tools.

Installing components

Your goal is to model a fairly realistic situation, in which an existing Java enterprise wants to add a Facebook application implemented in PHP. To do so, set up some of the components that you need in place for such an endeavor in the real world - Rational Application Developer, WebSphere Application Server, Zend Core (which includes a bundled Apache), and DB2.

Rational Application Developer, WebSphere Application Server, Zend Core and DB2

Rational Application Development is IBM's state-of-the-art Java development environment for the Eclipse IDE, which you will use along with WebSphere Application Server for the Java piece. WebSphere Application Server is IBM's J2EE application server, enabling you to create powerful, secure and easily maintained Java- and JSP-based applications. Zend Core is the world standard PHP engine, including a bundled production-ready Apache 2 Web server out of the box. DB2 is IBM's production-strength SQL database, and with the DB2 Express-C edition, it's completely free. Together these tools form a solid platform on which to develop your enterprise's applications. In this tutorial you will install the components on a Windows platform, but they are also available for Linux®.

Outfitting Rational Application Developer and WebSphere Application Server for Java development

To start, install Rational Application Developer and WebSphere Application Server to enable the Java side of development. First, download Rational Application Developer using IBM Installation Manager (see Resources). The download and installation are straightforward, but will take quite a while, depending upon the speed of your Internet connection.

For this tutorial, the server profile is named JakeAppServer. Start that profile's server by navigating to IBM WebSphere > Application Server 6.1 > Profiles > JakeAppServer. A command prompt window opens detailing the startup and closes the moment server startup finishes. You can verify that the server is running by opening the administrative console (opens in a browser).

Figure 3. The administrative console
The administrative console

Now that you've set up WebSphere Application Server, let's turn to the PHP side.

Setting up Zend Core For IBM for PHP and DB2 development

So now you're ready to set up Zend Core in order to introduce PHP to the mix. Download Zend Core for IBM (see Resources). You will be using the version of Zend Core for IBM that comes bundled with DB2 Express-C for ease of setup (see Figure 4).

  1. If you don't have a Zend account yet, you will be required to create one before proceeding with the download.
    Figure 4. Selecting the correct Zend Core to install
    Selecting the correct Zend Core to install
  2. When the InstallShield Wizard opens, choose the IBM DB2Express-C radio button.
  3. For simplicity's sake, use the Apache 2 Web server that comes bundled with Zend Core. Be sure to select the Install bundled Apache 2.2.2 option.
  4. Zend Core For IBM installation also installs DB2. You'll get a warning at this point telling you not to restart your computer at the end of the DB2 Express-C installation (see Figure 5).
    Figure 5. Zend Core installation warning concerning DB2 and computer restart
    Zend Core installation warning concerning DB2 and computer restart
  5. One installation quirk: when creating a password for the Local User account, the installer only accepts a password containing both letters and numbers (password123), but doesn't mention this requirement explicitly (see Figure 6).
    Figure 6. DB2 local user account setup
    DB2 local user account setup
    You can also specify not to autostart the DB2 instance at system startup just so you have more control over it, but that is a matter of preference.
  6. Allow the installation to create the First Steps profile to avoid Javascript warning messages in the browser when viewing DB2 First Steps pages by clicking Create profile (Figure 7).
    Figure 7. Creating DB2 First Steps browser profile
    Creating DB2 First Steps browser profile

Eventually you will arrive back at the Zend Core For IBM installer (having taken the detour through the DB2 installer), and should restart your computer before proceeding.

You now have DB2, Zend Core with its bundled Apache Web server, Rational Application Developer, and WebSphere ready to go. It's time to explore Facebook with respect to designing an application.

Designing a Facebook application

Ideally, you want to design an application that spreads virally -- one that users find incredibly useful or lots of fun to use or both, and that engages the user and their friends in interactions that spread it transparently throughout the Facebook network. You can't guarantee a hit application, which depends on the application's core concept, but you can guarantee that if you hit upon that concept, your application is integrated into the Facebook platform well enough that it promotes itself through viral marketing and virtual word-of-mouth. So in looking at the different pieces of Facebook and what the platform lets you do, you look through this lens: how to create an application that promotes lots of user interactivity, and leverages Facebook's integration points to widen your user base and encourage users to interact with your application whenever possible.

Anatomy of a Facebook application

Facebook provides your application with many points of integration into the Facebook user's environment: two primary areas called the application's canvas page and profile box, and a number of auxiliary integration points.

The Canvas Page

You visit an application's Canvas Page via the most prominent and omnipresent of these auxiliary points, the Left Nav -- a link in Facebook's left navigation bar, which frames all other pages within Facebook and lists all of the current user's installed applications (unless the user opts out of this when installing an application). For example, you can click on the Photos application's Left Nav link (see Figure 8).

Figure 8. Left Nav link
Left Nav link

Doing so brings up the Photos application's Canvas page, displaying a summary of your friends' recent updates to their photo albums, which they created using the Photos application (see Figure 9).

Figure 9. Photos Canvas Page
photos canvas page

Here you can click on one of your friends' photo albums and view it, still within the Photos Canvas Page (see Figure 10).

Figure 10. Viewing specific album within the photos Canvas Page
Viewing specific album within the photos canvas page

The profile box

The application's profile box is a widget on the user's profile page, usually displaying some sort of summary information about the user's activity within the application. In the case of the Photos application, you can see a couple of the user's most recent photo albums (see Figure 11).

Figure 11. The photos application's profile box
The photos application's profile box

Profile action links

Profile action links are links that an application can post to a user's profile, and they show up directly beneath the user's photo. Your profile action links can say and do different things depending on whether the user of the application or a visitor is viewing the profile at the time.

For example, here the photos application has posted a View Photos of Me action link in my profile (see Figure 12).

Figure 12. Photos application profile action link
Photos application profile action link

Clicking it takes you to the application's Canvas Page, displaying photos of me (see Figure 13).

Figure 13. Result of clicking photos application's profile action link
Result of clicking photos application's profile action link


An application's Canvas Page and Profile box allow users to express themselves, but applications also enable users to communicate with each other (and promote the application), often via Requests. A user can make a Request of another user within the context of an application such as requesting a friend confirmation in the Friends application, or inviting a friend to an event in the Events application. A user's pending Requests appear in the top-right box of their home page (see Figure 14).

Figure 14. Pending request summary on home page
Pending request sumary on home page

The user can view their full list of pending Requests by clicking any of the Requests shown (see Figure 15).

Figure 15. A user's Requests page
A user's Requests page

Requests are often invitations to add the application itself, or can require that the requested user add the application en route to fulfilling the Request, and are one piece of a Facebook application's word-of-mouth marketing (see Figure 16).

Figure 16. Request to add application
Request to add application

Applications that require user interactivity, such as a game, might make use of Requests to let the users play each other. The most frequent and fundamental example of this is the Friend Request, in which users identify their friends on Facebook and request confirmation of the friendship, further interlinking the social graph and enabling user interactivity for all other applications.

While Requests allow users to explicitly invite each other to interact with them within an application (and often to add the application themselves in doing so), the News Feed, Mini Feed, Message Attachments, Emails, and Notifications do so implicitly, and help keep your application in users' minds and promote its use.

The News Feed and Mini-Feed

The News Feed is an application appearing on a user's home page, that displays news items posted by the user's and the user's friends' applications, usually in response to some user's action within the application (see Figure 17).

Figure 17. The News Feed
The News Feed

Applications often announce News Feed items in response to an accepted Request, for example a user accepting a "friend confirmation" Request from the Friends application (see Figure 18).

Figure 18. Friend confirmation News Feed item
Friend confirmation News Feed item

The News Feed is essentially a public blog of user interactions within their applications, and promotes an atmosphere of fun and play throughout the network of friends. It entices friends to join in on the fun and interact with and install the applications themselves.

The Mini-Feed is a similar news feed on a user's profile, but only displays actions from that user's applications about that user, but nothing about their friends. As such, the user can also remove items from it. Applications can post items to a specific user's Mini Feed or both the Mini Feed and News Feed (see Figure 19).

Figure 19. The Mini Feed
The Mini Feed

Message attachments

Message attachments allow users to easily share their application content with their friends. Applications have a fixed FBML snippet that gets included in a user's Message Attachments pull-down when sending a message to another user's Facebook Inbox (see Figure 20).

Figure 20. Message attachment in message
Message attachment in message

A user can also include your application's Message Attachment when posting a note to another user's Wall, an application on their profile page (see Figure 20).

Figure 21. Message attachment in Wall post
Message Attachment in Wall post

Notifications and e-mails

Applications can send users Notifications, which appear on the user's Notifications page (see Figure 22).

Figure 22. Notifications page
Notifications page

These are line items visible only to the user receiving the Notification, and are separate from News Feed and Mini Feed stories.

For non-public Notifications, i.e. private communications from an application directly to a user, an application can send e-mails to users of an application or the user's friends, which are sent to the user's external email account (not their Facebook account) if they have that setting turned on.

An application's e-mails, News Feed actions, Notifications and message/wall attachments act to draw users into interacting with the application, triggering more such events, and thus support the viral spread of an application within the Facebook network.

The product directory

These word-of-mouth integration points promote the application and keep it active in users' minds, but users can also explicitly find applications to add via the Search box in the top-left corner of every screen (see Figure 23).

Figure 23. Searching for applications
Searching for applications

Users can also browse applications by clicking the Applications link, always visible directly beneath the search box in the left navigation column (see Figure 24).

Figure 24. The Application link
The Application link

Click the Applications link to open the Applications application's Canvas Page (see Figure 25).

Figure 25. The Applications application's canvas page
The Applications appplication's canvas page

You can manage your currently-installed applications and browse for new ones to add. Click Browse more applications to open another integration point for your application, the Product Directory (see figure 25).

Figure 26. The product directory
The product directory

Your application competes with the others for attention. It's useful to note that three of the four tabs along the top of the product directory. The first three, Recently Popular, Most Activity, and Most Active Users are functions of how popular the applications already are, meaning that the word-of-mouth marketing devices (Requests, News Feed, emails, and message/wall attachments), and creating an application that promotes user interactivity are paramount in its ability to spread, even when users explicitly look for new applications in the product directory. The application's first users can find it on the Newest tab, where you see the most recently published applications. From there it's up to the application to promote itself to become a hit on the social graph.

The About page

If an application in the product directory catches the user's eye, clicking its link in the product directory takes them to its About page (see Figure 27) where the user can learn more about the application, and hopefully add the application either to their profile or to a different page on Facebook.

Figure 27. An application's About page
An application's About page

Privacy settings

Finally, users can restrict an application's integration points within their environment via the Applications application, which lists all of your installed apps, allowing you to remove them or edit each one's settings. Click Edit Settings next to an application to open the standard Privacy Settings window that applies to any application (see Figure 28).

Figure 28. The standard privacy settings dialog
Privacy settings dialog

Here are the privacy settings described in detail:

  • Who can see this: Allows the user to specify who can see their installation of the Photos application. Options are:
    • My Network and Friends: Anyone in any of the user's networks (like New York, NY) and all the user's friends.
    • Friends of friends
    • Only friends
    • No one
    • Customize: Brings up a window allowing the user to customize which specific networks can view the app and which specific friends of this user cannot see the app.
  • Show this in my left-hand menu: Determines whether this application gets a Left Nav link in the user's list of installed applications (in their left navigation column).
  • Publish stories about this in my News Feed: Determines whether the application can post items to the user's News Feed (on their home page).
  • Publish stories about this in my Mini-Feed: Determines whether the application can post items to the user's Mini-Feed (on the Profile page).
  • Add a link below the profile picture to any profile: Determines whether your application can post profile action links
  • Allow this application to contact me via email: Determines whether your application can email the user. Note that this refers to the user's external email account; your application can't send email to a user's Facebook inbox.

After these standard privacy settings, an application can also provide its own custom configuration window, accessible via the Other Privacy Settings link in the standard Privacy Settings window (see Figure 29).

Figure 29. The Other privacy settings link in the standard privacy settings dialog
The Other privacy settings link in the standard privacy settings dialog

Now that you've reviewed the available points of integration for your application, let's look at how to create the content of your application for these various integration points.


You need to render content that Facebook can embed in its pages, but you can't just use straight HTML and Javascript like you would on your own Web site. Facebook needs to make sure that the content doesn't contain any malicious Javascript, such as any that wrecks the surrounding Facebook page, and also wants to make it as easy as possible for your application to include information from the Facebook environment in your rendered content.

Facebook's answer to these problems is FBML (FaceBook Markup Language), an XML language that Facebook translates into HTML when rendering your application's content, which provides your content with access to the surrounding data environment as Facebook renders your FBML on its servers. You can think of Facebook as a text pre-processor, like XSLT or PHP, that takes FBML content and translates it into HTML, substituting data about the user or environment for the various Facebook-specific tags. To replace the lost Javascript functionality, Facebook provides the FBJS language (FaceBook JavaScript). To simplify complex queries into the Facebook database, and reduce the number of calls needed to make to Facebook's servers, Facebook provides FQL, (FaceBook Query Language), a variant of SQL. Figure 30 illustrates the flow of information from your application server to the user's browser.

Figure 30. Flow of information from the application server to the user's browser
flow of information

Most of the FBML tags are identical to HTML tags and result in similar browser content when parsed, but FBML also provides many behavioral tags, and tags that extract information from the Facebook database and include it in your content. You'll delve into this more in Part 2.

As for FBJS (Facebook Javascript), it's just Javascript with some modifications. Facebook parses your usual-looking Javascript code and makes changes before passing it along to the browser. It also modifies the DOM a bit, putting restrictions on how you can access and modify elements. You'll look at the changes more in Part 2.

Facebook also provides powerful AJAX support via an AJAX object. All AJAX requests are proxied through Facebook's servers, which gives you the ability to return FBML code as the result of an AJAX request. Facebook processes the FBML code as it does any other, injecting Facebook data in place of the Facebook-specific tags like <fb:name>, and your AJAX call is returned an object that it can set as the "inner FBML" of a DOM element via the element's setInnerFBML() function. Facebook does not support the innerHTML attribute for security reasons, but a setInnerXHTML() function is in beta as of this writing.

Communication between WebSphere Application Server and Facebook's servers

Our application, running under WebSphere, must communicate with Facebook, and Facebook must communicate with your application. Facebook's communication with your PHP script is limited to Canvas Page requests, where users are taking some action within your application. When the user goes to your application's Canvas Page URL, e.g.,, Facebook proxies this request to your remote server URL, e.g., http://myserver.url/FacebookTestApp/index.php, and your index.php returns FBML for Facebook to render. Similarly, your FBJS code makes an AJAX request, which goes through the same proxying and calls your server for the response.

Your application also needs to communicate with Facebook, either pulling or pushing information during a request. It does so via Facebook's REST interface, an HTTP interface that exposes an API of functions as URLs you can call with various request parameters specific to the function, and that return XML or JSON. Luckily, you don't have to worry about the details of these HTTP calls or the return data because Facebook provides PHP, Java and Javascript client libraries -- wrappers around the REST interface that handle the construction of the HTTP requests and marshalling of return data into objects usable within the client library's language.

Using the client library

The client library provides a Facebook client API object, a proxy object that turns our method calls into requests to Facebook's servers. For example, to get the current user's friends, you only need to call a function on the Facebook object (see listing 1).

Listing 1. Obtaining the current user's friends via the PHP client library
$friends = $facebook->friends_get();

We can also push information to Facebook (make updates to the data). For example, the profile box works differently than the canvas page (see The Profile Box and The canvas page). Rather than waiting for Facebook to query your server for the contents of a user's profile box, you have to explicitly push that content every time you want to change it. Facebook then caches the profile box content on its servers. This makes a lot of sense because if the profile box content were not cached on Facebook, Facebook would hit your server every time anyone viewed a user's profile containing your application, and users spend a lot of their time on Facebook visiting each other's profiles, and hence loading the profile boxes of all the applications installed on them. For a popular application this would put tremendous load on the server, and would also introduce a latency in loading Profile Pages. To change the content of your application's profile box on a user's profile, you again just call a method on the $facebook object provided by the PHP client library (see Listing 2).

Listing 2. Setting the content of your application's profile box on the current user's profile page.
$facebook->profile_setFBML ('New profile box content', $user);

Each of these method calls make an explicit request to Facebook. As your application gets more complex, your PHP code has to query Facebook for more and more complex data, and data that depends upon the results of previous function calls. For example, you might want to fetch the first names of all people tagged in the current user's photos, which would require that you first call Facebook for all of the user's albums, then for all the photos in those albums, then for all the photo tags of those photos, then for those photo tags' users -- a lot of work, a lot of requests to Facebook's servers, and a lot of PHP code.


Instead, you can use a single FQL query (Facebook Query Language), a variant of SQL that Facebook provides to query its database and core application's data directly. In a nutshell, FQL only allows one table in the from clause of a query, but allows sub-queries in the select and where clauses, so the following FQL query would fetch the same information as described above (the first names of photo-tagged users), but in a single request, more concisely and with code that is much easier to read and fun to write (see Listing 3).

Listing 3. FQL example -- selecting the first names of all users tagged in a user's photos
select first_name from user 
where uid in 
(select subject from photo_tag where pid in
    (select pid from photo where aid in
        (select aid from album where owner = 563830447)))

In Listing 3, 563830447 is the author's Facebook ID. This FQL request returns XML containing the first name of the only photo tag found among the author's photos, and is an example of a Facebook REST response (see Listing 4).

Listing 4. FQL query response
<?xml version="1.0" encoding="UTF-8"?>
<fql_query_response xmlns="" 
     xmlns:xsi="" list="true">

You can verify this, and experiment with FBML snippets, using Facebook's developer test console, found at (see figure 31).

Figure 31. The Facebook API test console
The Facebook API test console

Using FBML, FBJS, FQL and the Facebook client libraries, you can develop an application well integrated into the environment and providing powerful functionality. Now you're ready to create your application.

Starting Facebook application development

To start application development, first tell Facebook's servers about your application, set up necessary configuration options, create some database tables in DB2, then finish with a small prototype of your application to confirm that it's correctly installed in Facebook.

Telling Facebook's servers about your application

If you don't have a Facebook account, the first step is to create one at Facebook sends a confirmation email to the address you provide as the account's login ID - click on the link in the email to complete your registration.

Next, add the Facebook Developer Application to your account so you can add and manage your Facebook applications. Once logged into your Facebook account, go to, which redirects (see Figure 32).

Figure 32. Adding the Developer application
Adding the Developer application

Keep the defaults and click Add Developer. You're ready to develop your first application (see figure 33).

Figure 33. Developer application upon first adding it
Developer application upon first adding i

For future applications, you can get to the Developer application's canvas page via the Left Nav link installed in your list of applications. To add an application, click Apply for an Application Key, and start configuration (see Figure 34).

Figure 34. Creating a new application
Creating a new application

Though you only need to provide a name for an application and accept the terms of the Facebook platform, your application won't be terribly useful without the information you provide under Optional Fields (see Figure 35). Keep in mind that you can edit this settings page any time you need to in the future after first saving it. For now just fill in the fields necessary to get started. In Part 2, when you develop the application, you'll return to the settings page.

Figure 35. Application configuration -- Optional Fields
Application configuration -- Optional Fields
  • Developer Contact E-mail and User Support E-mail: Contain your Facebook login email; the first is how Facebook contacts you if they have a problem with your application, and the second is how users contact you via your application's help page.
  • Canvas Page URL: The URL of your application's Canvas Page on Facebook, e.g., The URL must be unique among all Facebook applications, but once you've typed enough characters, a Javascript indicator tells you as you type whether the URL is available or not, so there's no need to search for the name in the application directory first to ensure uniqueness (see Figure 36).
    Figure 36. Entering a unique Canvas Page URL
    Entering a unique Canvas Page URL
  • Callback Url: Not really a callback per se, but a proxy for the URL of the application on the remote server. In this case it's the URL of the PHP script running on your Apache 2 server that outputs the canvas area content, e.g.,

    The combined effect of the Canvas Page URL and Callback URL is that users can go to the Canvas Page URL in their browser to view your application's Canvas Page, and Facebook fills in the canvas area on that page by calling your remote PHP script. Facebook never exposes the Callback URL to anyone but the application's developer.
  • Use FBML / Use iframe: Tells Facebook whether your Canvas Page Callback URL returns FBML that Facebook should then translate into HTML, or straight HTML that Facebook instead displays verbatim in an iframe, as the contents of the canvas area.
    Since FBML provides an <fb:iframe> tag anyway, and provides so much functionality in terms of accessing the Facebook environment while rendering FBML content, there's little reason not to use FBML. If you have an existing HTML/Javascript component that you want to embed, you can include it verbatim as the source of an <fb:iframe> within your FBML Canvas Page.
  • Application Type: Select Website to specify that your application is embedded, i.e., used directly within the Facebook Web site. Desktop specifies that the application is a desktop application or browser extension that communicates with Facebook's servers, for example, a desktop application that uploads and downloads one's Facebook photos en masse.
  • IP Addresses of Servers Making Requests: For extra security, specify your remote server's IP address so that only your server can make Facebook requests (pulling or pushing data) on behalf of your Facebook application. If your application ran on multiple IP addresses, you'd specify them all here.
  • Can your application be added on Facebook?: Click Yes. This specifies whether users, including developers, can add your application to their accounts. Specify Developer Mode below to restrict access to developers for the moment. Specify the names of other developers that can access the application while it's in Developer Mode under Developers.
  • Default Iframe Canvas Size Option: This option is only relevant if you selected the iframe radio button instead of FBML as the type of content the Callback URL returns. In the case of selecting iframe, Facebook does not just throw the content into a plain HTML <iframe> tag in the canvas area, it uses FBML's equivalent <fb:iframe> tag, which provides some additional custom functionality, including two mutually exclusive boolean attributes, smartsize and resizable, that specify how the iframe is sized. Smart size tells Facebook to size the iframe to fit the canvas area, and resizable specifies that iframe's size can be set using the Javascript API. Since you selected FBML, this option is irrelevant to your application.

Installation Options and Integration Points

Selecting Yes for Can your application be added on Facebook? revealed two more sections of options, Installation Options and Integration Points (see Figures 37 and 38).

Figure 37. Application configuration -- Installation Options
Application configuration -- Installation Options
  • Who can add your application to their Facebook account?: For your application, select Users, specifying that users can add the application to their accounts. You can also specify that the application can be added to specific pages or types of pages in Facebook.
  • Application Description: Put any text that you want to appear on the application's add page when the user is prompted to add the application.
  • Default FBML: This is the FBML that initially renders on the user's Profile page, until your application updates their profile explicitly using the PHP client library (more on this in Part 2 of this tutorial). For now you're just putting a placeholder there to get a prototype application running.
  • Default Profile Box Column: Select Narrow. This specifies that your app appears in the narrow left column of the Profile page instead of the wide one.
  • Developer Mode: Select this to allow only developers of the application to add it to their accounts. The application isn't released into the Product Directory yet, so it's unlikely that any users will find it, but if they know the URL they can access it.

The Integration Points section lets you specify the more auxiliary integration points within the user's environment. For now just specify the Side Nav URL, which is the URL of the link that appears in your Application list (the Left Nav link). Make sure that the URL is identical to the Canvas Page URL, and that it is all lower-case. Canvas Page URLs are case-sensitive, and even if you specify a mixed-case Canvas Page URL, it gets converted to all lowercase, so make sure you specify it in lowercase here too or this link produces a Page Not Found error.

Figure 38. Application configuration -- Integration Points
Application configuration -- Integration Points

Submit the settings, and you'll see a summary page (see Figure 39).

Figure 39. Application settings summary page
Application settings summary page

To change the settings click Edit Settings on the right side.

Finally, to test the setup, create a barebone index.php to confirm that Facebook is pulling your content correctly via the Callback URL proxy. You can connect to Facebook via the PHP client library, and that Facebook renders your FBML. Create a directory under your Apache 2 server for your application, C:\Program Files\Zend\Apache2\htdocs\fb_stock_demo. Then go to and download the PHP Client Library in tar.gz form (see Figure 40).

Figure 40. Downloading the PHP client library
Downnloading the PHP client library

The facebook-platform directory inside contains a client directory, containing the Facebook PHP client code. Copy this client directory to the directory under Apache 2 just created, creating C:\Program Files\Zend\Apache2\htdocs\fb_stock_demo\client.

Next you'll create index.php itself, under C:\Program Files\Zend\Apache2\htdocs\fb_stock_demo (see Listing 5).

Listing 5: A simple index.php for the Canvas Page

// the facebook client library
include_once './client/facebook.php';

// the values on our application's settings summary page
$api_key = 'YOUR_API_KEY';
$secret  = 'YOUR_SECRET';

// connect to Facebook, require app installation
$facebook = new Facebook($api_key, $secret);

// obtain the user's id
$user = $facebook->require_login();


<div style="border: solid black 1px; padding: 25px;">
  <h2>Hi <fb:name firstnameonly="true" uid="<?=$user?>" 
  Welcome to the Developer Works Stock Broker Demo.  Coming soon... 

The first line includes the Facebook PHP client library. Set $api_key and $secret to the API Key and Secret values on your application's summary page. The next line connects to Facebook, creating a proxy object you will use to communicate with Facebook's servers. Using the proxy object, you require that the user viewing your application be logged into the application when doing so, and obtain their user id, to use it in the <fb:name> tag below. The FBML itself is mostly plain HTML that gets rendered similarly. The <fb:name> tag gives a taste of FBML -- Facebook turns that tag into the name of the user viewing the application (because you're passing in that user's id). This tag provides a number of options and lots of functionality with regard to what text it actually produces. In this example, specify useyou="false" to override the default, which would render the word you instead of the user's first name because the user id specified equals that of the user viewing the application. In this case you want to address your viewer by name to greet them.

Place this index.php in your application's directory under Apache 2's htdocs, C:\Program Files\Zend\Apache2\htdocs\fb_stock_demo, and go to your application's Canvas Page URL in the browser, e.g. (see Figure 41).

Figure 41. Adding your application en route to its Canvas Page
Adding your appplication en route to its Canvas Page

Leave everything checked, click the add button at the bottom, and you arrive at your Profile page. Scroll down, and you'll see your application's profile box, containing the default FBML code you provided (see Figure 42).

Figure 42. Your application's Profile Box
Our application's Profile Box

Scroll back up to view your Application list and see that your application has added its Left Nav link (see figure 42). You may have to click 'more' to show the full list of apps.

Figure 43. Your application's Left Nav link
Our application's Left Nav link

Click the app's link, and admire your nascent Canvas Page (see Figure 44).

Figure 44 Your application's Canvas Page
Our application's Canvas Page

While it's more friendly than useful at the moment, you now have your barebone Facebook application up and running.

Setting up the backend DB2 database

Now you need to define some database tables for your application, which you'll do in this section.

Defining the tables

A stock brokerage has traders and stocks, and traders buy and sell shares of stocks to maintain their "positions" on each of the stocks -- how much of the stock they own or have sold the stock short. The "brokerage" prefix on all the table names specifies a schema for the tables; otherwise, they would go in the default schema.

Use DB2's command line interface to create the tables. In a command prompt window, open a DB2 command prompt window by typing db2cmd, and then in the DB2 command prompt that opens, start a DB2 session by typing db2start. DB2 will output: SQL2063N DB2START processing was successful.

Next, create a database, called "stocks": by typing db2 create database stocks, which outputs The CREATE DATABASE command completed successfully.

Connect to the database by typing db2 connect to stocks. DB2 will output Database Connection Information, the version of DB2, the SQL authorization ID and the database alias, "stocks".

Start creating your tables (see Downloads for all of the sql used in this section). First, create a trader table, leaving it barebone for the purposes of your demo application (see Listing 6).

Listing 6. Creating the trader table in DB2
db2 create table trader ( 
id int not null primary key generated always as identity,  
username varchar(30) not null unique,  
password varchar(30) not null)

The generated always as identity is a feature of DB2 7.1 and later, providing a simple sequence mechanism; you never have to specify the value of the primary key when inserting rows into the table.

Using the same technique, create a table of stocks in Listing 7.

Listing 7. Creating the stock table in DB2
db2 create table stock ( 
    id int not null primary key generated always as identity, 
    ticker varchar(5) not null unique)

Next create the table storing the meat of the data, the stock trades themselves. Each trade represents a purchase or sale of shares of a stock, and is associated with a trader and a stock. A trade stores the number of shares (a negative value denotes a sale or shorting of a stock, a positive value a purchase), and the price of each share at the time of the trade. Note that share_price is an int because you store share_price as a number of cents to avoid floating-point errors (see Listing 8).

Listing 8. Create the trade table in DB2
db2 create table trade ( 
    id int not null primary key generated always as identity, 
    trader_id int not null references trader(id) on delete cascade, 
    stock_id int not null references stock(id) on delete cascade, 
    shares int not null, 
    share_price int not null, 
    created_on timestamp not null)

For the purposes of this demo, when you need a trader's current position on a stock, you'll sum up the results of that trader's trades on that stock, as opposed to caching the trader's current position in a separate table as a snapshot at the time of each trade.

Finally, rather than add a facebook_user_id directly to the trader table, use a separate facebook_user table, because you're adding a Facebook application to an existing stock brokerage's online system (see listing 9)

Listing 9. Creating a separate facebook_user table in DB2
db2 create table facebook_user (
    facebook_user_id int not null primary key,
    trader_id int not null references trader(id) on delete cascade,
created_on timestamp not null)

You only insert a facebook_user row when a Facebook user adds your application to their Facebook account, at which point they log into your system so you can link up their Facebook id with their existing trader record in your existing system. If they don't have an existing trader record at that point, ask them to create one on your system; the Facebook application helps promote new registrations on your existing trading site.

Populating with sample brokerage accounts

To give your application some data to play with, populate the tables with a little information. First create a couple of traders (see listing 10).

Listing 10. Creating sample traders in the database
    db2 insert into trader (username, password) values ('jake1', 'password1')
db2 insert into trader (username, password) values ('jake2', 'password2')

Next create some stocks (see Listing 11) in the database.

Listing 11. Creating some sample stocks in the database
    db2 insert into stock (ticker) values ('JAKE')
    db2 insert into stock (ticker) values ('NYC')
db2 insert into stock (ticker) values ('ABC')
db2 insert into stock (ticker) values ('USB')
db2 insert into stock (ticker) values ('UCLA')
db2 insert into stock (ticker) values ('KRZY')

Then you'll start your two traders off with an initial purchase of 100 shares of 3 stocks at various prices (see Listings 12 and 13).

Listing 12. Creating sample trades for trader "jake1"
    db2 insert into trade (trader_id, stock_id, shares, share_price, created_on) 
             select,, 100, 4400, current timestamp 
        from trader, stock 
        where trader.username = 'jake1' 
        and stock.ticker = 'JAKE'

db2 insert into trade (trader_id, stock_id, shares, share_price, created_on) 
             select,, 100, 2300, current timestamp 
        from trader, stock 
        where trader.username = 'jake1' 
        and stock.ticker = 'NYC'

db2 insert into trade (trader_id, stock_id, shares, share_price, created_on) 
             select,, 100, 6400, current timestamp 
        from trader, stock 
        where trader.username = 'jake1' 
        and stock.ticker = 'ABC'

Listing 13 creates samples traders for trader "jake2".

Listing 13. Creating sample traders for trader "jake2"
db2 insert into trade (trader_id, stock_id, shares, share_price, created_on) 
             select,, 100, 1200, current timestamp 
        from trader, stock 
        where trader.username = 'jake2' 
        and stock.ticker = 'USB'

db2 insert into trade (trader_id, stock_id, shares, share_price, created_on) 
             select,, 100, 10200, current timestamp 
        from trader, stock 
        where trader.username = 'jake2' 
        and stock.ticker = 'UCLA'

db2 insert into trade (trader_id, stock_id, shares, share_price, created_on) 
             select,, 100, 5200, current timestamp 
        from trader, stock 
        where trader.username = 'jake2' 
        and stock.ticker = 'KRZY'

To confirm that you're all set up, perform some select statements. Start by typing select * from trader. DB2 will output 2 record(s) selected.

Then type select * from stock. DB2 will output 6 record(s) selected.

Then type select * from trade. DB2 will output 6 record(s) selected, one per sample trade that you set up. Since you don't have any sample data for the facebook_user table yet, there's nothing to confirm.

So at this point you have your tools installed, your barebone Facebook application running, and a database ready for action. You're ready to start developing your Facebook application in Part 2!


Facebook provides a rich social graph of users and rich set of integration points that you can exploit in developing an interactive, social application. Using IBM's DB2 database, Rational Application Developer environment and WebSphere Application Server for the Java side, and Zend Core for the PHP side of your application, you can work with both technologies as needed within your enterprise. Here you got a first look at Facebook, installed your components, took a tour of Facebook's integration points to guide you in developing an application, took a brief look at FBML, FBJS, and FQL, and started development with something barebone on the PHP side. You're now ready for Part 2, where you'll dive in and implement the application using all these technologies.


Part 1 example codefacebook-article-listings.zip3KB



Get products and technologies


developerWorks: Sign in

Required fields are indicated with an asterisk (*).

Need an IBM ID?
Forgot your IBM ID?

Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.


All information submitted is secure.

Dig deeper into Rational software on developerWorks

Zone=Rational, WebSphere, Information Management, DevOps
ArticleTitle=Mastering Facebook application development with PHP, Rational Application Developer, WebSphere Application Server, and DB2, Part 1: Set up the components