Create Facebook applications with CodeIgniter

Integrating the Facebook SDK

Learn how to incorporate the Facebook SDK into the CodeIgniter framework, using the available functions to create applications.

Share:

Thomas Myer (tom@tripledogs.com), Consultant, Triple Dog Dare Media

Thomas MyerThomas Myer is a consultant, author, and speaker based in Austin, Texas. He runs Triple Dog Dare Media and tweets as @myerman on Twitter. You can reach him at tom@tripledogs.com.



24 August 2010

Also available in Chinese Japanese

This article shows you how to get the sample Facebook application working with the CodeIgniter framework for PHP. There are plenty of really great articles out there on Facebook development, of course, and a handful of good ones on using CodeIgniter to build applications, but this one takes into account the latest PHP SDK made available by Facebook.

Instead of showing you how to take an existing wrapper library for the Facebook SDK, you will learn how to easily wrap the SDK yourself and then use it in a quick way. This article also shows you all the steps you need to take to register your application with Facebook and how to set up CodeIgniter to start working with Facebook, and it covers the basic stuff you might encounter during this process.

As this article covers quite a bit of territory, a few prerequisites will help you keep up. First, you need to know something about PHP and CodeIgniter. You don't need to know a great deal, but some familiarity will help you get started. You also need access to your own publicly available web server. Applications like the one you're going to create always reside on their own server and are then served up in iframes inside Facebook: Merely coding from localhost won't work here. Last but not least, you need a Facebook account, because you're required to register your application with Facebook.

The basics

Before getting into details, here's a quick overview of Facebook applications and CodeIgniter.

Facebook application basics

You can build different kinds of Facebook applications, including mobile and web applications—the focus of this article. Basically, all a Facebook application really consists of is an iframe that runs on Facebook.com and calls code on your server.

The code on your server needs to follow a few rules for integrating with Facebook sessions and using the right functions to access various functionality (like listing your friends or events you've RSVP-ed to), but that's about it. You can add all kinds of functionality to your application, such as saving different data into database tables, to add value to the Facebook experience.

If you do things right, your Facebook application will be something that Facebook users will sign up for and tell others about, which means that you will need to think a bit about bandwidth issues. Every time you get a new user or someone interacts with your application, the Facebook servers make a request that hits your server, so plan for that.

What kinds of applications can you build on Facebook? Take a look at the Facebook Developer Showcase (see Resources for a link), and you'll see hundreds of live applications in a variety of categories—news, sports, social good, utilities, reviews, local, and more. For example, the Pandora application integrates the popular personalized music service with Facebook. Facebook users can now easily share their music discoveries with their friends and further personalize their enjoyment of music. Similarly, the IMDb Facebook application allows Facebook users to further engage with their favorite movies, actors, and directors and to share their thoughts directly with Facebook friends.

The SimplyHired application combines the power of Facebook friend networks and recommendations with a job search engine to get customized job recommendations. The TripAdvisor application allows Facebook users to "like" properties and destinations and to share key aspects of their travel experience with their friends.

In this article, there won't be space for more than a basic application, but if you want to be a Facebook application developer, you would do well to study the market and see what's out there.

CodeIgniter basics

CodeIgniter is a model-view-controller (MVC) framework for PHP created by EllisLab. As of this writing, it's at version 1.7.2. Although many MVC frameworks are available for PHP (such as Symfony and CakePHP), the chief differentiator that sets CodeIgniter apart is the flexibility it derives from being so lightweight.

With CodeIgniter, as with other MVC frameworks, you divide your code into different functional areas:

  • Models contain any and all code that relates to your database and other data structures. If you had a table called pages, you'd have a model for it and functions within that model for selecting, creating, updating, and deleting records from that table, among other things.
  • Views contain all your display and UI elements—your JavaScript code, CSS files, HTML, and even PHP.
  • Controllers hold it all together. Each function in a controller represents a destination or route. If you had a destination called /about, your controller would have a function called about().

If you haven't worked with an MVC framework before, these three bullet points offer little clue as to the power behind this organizational scheme. Once you start thinking in terms of MVC, your perspective about and attitude toward PHP development changes radically.

For example, instead of tucking database query code in every available nook and cranny of your project, you organize all of it into models. And to select a page from your database table, you use a function from the pages model.

Similarly, if you need to update the look and feel of a certain page, you work with the views. You don't mess around with the controller. Likewise, the controller is where you add destinations and other controlling code for your application; you don't put any of that stuff in your model.

Unlike other MVC frameworks, there are no strict naming conventions for your models, tables, and controllers in CodeIgniter. For example, you don't have to name your table in the plural form (pages) and your model in the singular (page) to tie the two together. Your database tables don't have to contain certain fields with certain names, either: If you don't have a primary key field named id, the world won't end.

Furthermore, you can choose to use as much or as little of the framework as you need to get the job done. Typically, your application will have a series of controllers, all of which will pull data from models and then display data in views. In some cases, though, your projects will only have controllers and views—a perfect solution if you're building a static web site without a database back end.

Another interesting fact about CodeIgniter is how easy it is to integrate with other code. In most cases, if you want to integrate an external SDK, simply add it to the plugins folder with a specific naming convention (for example, in this article, you rename the facebook.php library file to facebook_pi.php), and you're ready to go.


Getting started

So, let's get started with your first Facebook application written with CodeIgniter. This is a multistep process that requires a bit of setup; by the end of it, you'll have everything you need to create a Facebook application.

To install and configure CodeIgniter, perform the following steps:

  1. Download and install CodeIgniter (see Resources).
  2. Open the downloaded .zip file, and extract the contents to a publicly available web server.

    You can deploy CodeIgniter into the root of an existing domain, into a sub-domain, or to a folder off the root of an existing domain.

  3. Open the system/application/config/config.php file in a text editor, and update the $config['base_url'] variable so that it points to where you installed CodeIgniter. Be sure to upload the changes to the server.
  4. Test CodeIgniter by opening a browser and visiting the URL that houses the CodeIgniter application (for instance, example.com/test or test.example.com).

    You should see the generic message, "Welcome to CodeIgniter!" If you don't, you've missed something along the way. Reinstall CodeIgniter and start over.

    It's important that you run this test, as you need to be able to confirm that your CodeIgniter base code is working properly and isolate any problems that might occur with the connection between Facebook and your server.

    Note: If you're having trouble seeing the generic message from CodeIgniter, it might be that you're having DNS trouble—particularly if this is a new domain or sub-domain. If that's the case, you might need to give it some time before you move on to the next step.

  5. Go to Facebook.com/developers and set up a new application.

    If this is the first time you've done this, perform the following steps:

    1. Click Allow to provide access to the application.
    2. On the Developer page, click Set Up New Application.
    3. On the Create Application page, enter a name for your application (it can be anything you want), select Agree, and then click Create Application, as shown in Figure 1.
      Figure 1. Creating an application
      The 'Create Application' screen in Facebook, showing a field for 'Application name,' radio buttons for agreeing or disagreeing to the Terms, and a 'Create Application' button
    4. On the Edit Application page, on the Basic tab, note the application ID, API key, and secret—these are unique to each Facebook application, and you'll need this information to do your job.
      Figure 2. The Basic tab
      Screen shot of the Edit Application page, Basic tab
    5. Type a description for your application, and add an icon, logo, and other information. (You can also come back and do this later.)
    6. Click the Canvas tab, and enter the canvas page URL (that is, the destination on Facebook.com that people will go to get your application) and the canvas callback URL (the URL where you installed CodeIgniter plus a directory path to a controller.)

      In the example in Figure 3, the canvas callback URL is http://www.example.com/index.php/home/, which is where you'll create a home controller in your installation and where the application will do its heavy lifting.

      Figure 3. The Canvas tab
      Screen shot of the Edit page, Canvas tab, showing the fields 'Canvas Page URL' and 'Canvas Callback URL.'
    7. Click the Connect tab (see Figure 4), and enter your connect URL.

      This URL should be the same as the canvas callback URL you entered earlier. Note that if your application lives in a sub-domain (for example, foo.example.com), type your base domain in the Base Domain field (that is, example.com).

      Figure 4. The Connect tab
      The Edit page, Connect tab, showing the Facebook connect settings
    8. Click Save Changes. You should see a summary page if all has gone well (see Figure 5).
      Figure 5. The summary page
      A sample page indicating at the top that your changes were saved.
  6. Download the PHP SDK (see Resources).

    The download contains a src/facebook.php file (this is the main library) and an examples/example.php file.

  7. Create a simple application in CodeIgniter:
    1. Rename the facebook.php file you just downloaded to facebook_pi.php, and put it in the system/application/plugins folder of your CodeIgniter code.

      If no plugins folder exists, create it now and put your newly renamed file in it.

    2. Copy the example.php file into the system/application/views folder.
    3. Open a text editor, and create a simple controller called Home. Copy and paste the code in Listing 1 into that file, and then save it as home.php in the system/application/controllers directory.
      Listing 1. A bare-bones controller
      class Home extends Controller {
      
      	function Home()
      	{
      		parent::Controller();	
      		$this->load->plugin('facebook');
      	}
      
      	function index()
      	{
      		$this->load->view('example');
      	}
      }

      Here, you're creating a home controller so that your route will activate properly. Remember that the Facebook application is looking for example.com/index.php/home, so this particular controller will respond to that request. The index() function will load any requests that come bare to that controller, just like an index.html or index.php file will on a static server.

      When you initiate the class, the constructor loads your Facebook plug-in. (Wait a minute, you ask: When did I create a Facebook plug-in? Remember what you did with the facebook.php file, renaming it to facebook_pi.php and placing it in the plugins folder? That's all you had to do to make it available to CodeIgniter as a plug-in.)

      In the index() function, you simply load the example view (no need to put the .php part in), and all that remains is two minor edits to the example.php file in the views folder.

    4. Load the example.php file into a text editor, and remove the first line—the one that does an include of the facebook.php line. CodeIgniter did that already when you ran $this->load->plugin('facebook');.
    5. Change the lines in Listing 2 to match the application ID and secret you got from Facebook when you created your application.
      Listing 2. Editing the view
      // Create our Application instance.
      $facebook = new Facebook(array(
        'appId'  => 'some-value',
        'secret' => 'some-other-value',
        'cookie' => true,
      ));
    6. Save your work, and then push your updates to the server.

You've been working hard on the initial setup, and when you get back from your well-earned break, you need to test to make sure you've done everything right.


A final test

As a final test of what you've been doing, simply visit the URL you assigned to your application in Facebook—in other words, the http://apps.facebook.com/YOUR_APP_NAME address. If you've done everything correctly, you should see a page like the one in Figure 6 in your browser (except of course, you'll see your own Facebook data and not mine!). If you don't see such a page or if errors come up, you may need to enable cURL and/or run a version of PHP that supports json_decode(). The Facebook SDK will error out if neither of these is available on your server.

Figure 6. The running application
A screen shot of the author's Facebook application, entitled 'PHP-SDK'

If you want to compare what the raw code looks like outside of CodeIgniter, you can visit fbtest.tripledogs.com—a little sub-domain that I set up that has the raw SDK running without CodeIgniter. If you compare that code with what you have running now, you'll see that it only took a few extra minutes to achieve the same results, but now you've got the power of the CodeIgniter framework at your disposal.


Conclusion

At this point, you know how to get started with your own Facebook application. With any luck, using this approach, you can easily move on to more complex undertakings.

Resources

Learn

Get products and technologies

Discuss

Comments

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 Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=512894
ArticleTitle=Create Facebook applications with CodeIgniter
publish-date=08242010