Silverlight and PHP, Part 2: Creating a Simple Twitter Client

Tweet

In my previous article, I talked about how to create a simple web service in PHP, and consume that service from Silverlight. This article will draw on the concepts in that article to create a very simple Twitter client in Silverlight.

Over the past few years, services like Twitter have become very popular, not just because of their consumer focus, but also because they open up their APIs for developers to consume. Twitter, for example, exposes a lot of data via RSS and ATOM feeds, so loading data is as simple as a well-structured URL call. Silverlight is then able to process this feed and extract the content (in this case, Tweets) from it.

The application that we’ll build in this article will allow you to enter a Twitter search term, and display the tweets received in Silverlight. Unfortunately, this process isn’t as simple as loading a URL from Silverlight, because of something known as cross-domain access policy.

Before we begin, it’s highly recommended that you read my previous article on PHP services and Silverlight, because the basic information I’ve covered there is prerequisite to what we’ll discuss here.

Again this time, we have a Microsoft-sponsored Article Quiz to test your learnings when you’re done.

What Is Cross-domain Access?

Silverlight and other RIA technologies such as Adobe Flash are restricted to accessing data from their domain of origin.

For example, if you host your Silverlight application at http://www.mysite.com, you’re free to load any URLs from this site from within your Silverlight application. However, if you try to load something from http://www.yoursite.com, the call will be blocked and you will receive a 404 error in Silverlight—even if the URL is correct.

One way to get around this limitation is to place a clientaccesspolicy.xml file in the root of your site. Silverlight will look for this file, and if it’s present (and if it has the right settings), Silverlight will gain permission to access URLs on the other server. Note that images and other media are not subject to this restriction. This is the same restriction that applies to JavaScript in the browser. For more information on cross-domain access in Silverlight, see http://msdn.microsoft.com/en-us/library/cc645032(VS.95).aspx.

The Solution

There is a rather simple way to work around these cross-domain access restrictions. Twitter does not provide a clientaccesspolicy.xml file that Silverlight can use to access the Twitter APIs. However, the restrictions only apply to Silverlight—not to any server side code you write. So one workaround is to create on your server a web service that Silverlight can access freely, without domain restrictions, and which will act as a proxy to load the Twitter data.

All this might sound like a lot of extra work, but as we’ll see, it’s actually rather simple. Let’s begin by creating the PHP web service to access the twitter searches.

Searching Twitter from PHP

In my previous article, I described how to set up a web service in PHP. All the steps you’ll need to work through to set up this PHP service are the same, with a few changes to the WSDL (Web Service Description Language) file and the PHP service file. Also, the index.php file has been changed to point to the new Silverlight XAP package (the file you need to build in Visual Studio, then copy across to your PHP site).

Start by creating a new file to hold the new web service’s WSDL, called twitterSearchService.wsdl. This is the file that PHP uses to configure the exposed service. It’s also used by Visual Studio to create classes to access the service.

The file needs to have the following content (assuming your service lives in a directory called php in your web root, otherwise simply change the paths as needed):

Example 1. php/twitterSearchService.wsdl

<wsdl:definitions xmlns="http://schemas.xmlsoap.org/wsdl/"     xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"     xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"     xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"     xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:tns="http://schema.example.com"     targetNamespace="http://schema.example.com">  <wsdl:types>    <xsd:schema targetNamespace="http://schema.example.com"/>  </wsdl:types>  <message name="getTwitterSearchRequest">    <part name="searchText" type="xsd:string"/>    <part name="lastTwitterId" type="xsd:string"/>  </message>  <message name="getTwitterSearchResponse">    <part name="getTwitterSearchReturn" type="xsd:string"/>  </message>  <wsdl:portType name="twitterSearchServicePortType">    <wsdl:operation name="getTwitterSearch">      <wsdl:input message="tns:getTwitterSearchRequest"/>      <wsdl:output message="tns:getTwitterSearchResponse"/>    </wsdl:operation>  </wsdl:portType>  <binding name="twitterSearchServiceBinding"       type="tns:twitterSearchServicePortType">    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>    <wsdl:operation name="getTwitterSearch">      <soap:operation soapAction="urn:ageService/getTwitterSearch" style="document"/>      <wsdl:input>        <soap:body use="literal"/>      </wsdl:input>      <wsdl:output>        <soap:body use="literal"/>      </wsdl:output>    </wsdl:operation>  </binding>  <wsdl:service name="twitterSearchService">    <wsdl:port name="twitterSearchServicePort"         binding="tns:twitterSearchServiceBinding">      <soap:address location="http://localhost/php/twitterSearchService.php"/>    </wsdl:port>  </wsdl:service></wsdl:definitions>


This file is only slightly different from the WSDL that was used in my previous article: the names have changed, a second parameter has been added to the search request, and the response return type was changed from integer to string.

Next, create a second file called twitterSearchService.php. You’ll note that the WSDL file references this filename.

Let’s start by configuring the PHP file to expose the web service. Inside the <?php tags, add the following code:

Example 2. php/twitterSearchService.php (excerpt)

ini_set("soap.wsdl_cache_enabled", "0"); $server = new SoapServer("twitterSearchService.wsdl"); $server->addFunction("getTwitterSearch"); $server->handle();


As in the previous article, this code loads the WSDL file, and adds a pointer to a function called getTwitterSearch, which will be used as the implementation code that executes the web service call.

With this in mind, you need to create a new function called getTwitterSearch.

Above the code you just pasted into your file, create a new function called getTwitterSearch with two parameters: searchText and lastTwitterId. These parameters will be combined into a URL to access the Twitter Search API. While searchText is fairly obvious, lastTwitterId may not be. It’s used to instruct the search to only find tweets that have been published since the last tweet in the previous search. This prevents the same tweets from being returned in subsequent searches.

Example 3. php/twitterSearchService.php (excerpt)

function getTwitterSearch($searchText, $lastTwitterId) {  ⋮}


The code for the function is pretty simple:

Example 4. php/twitterSearchService.php (excerpt)

function getTwitterSearch($searchText, $lastTwitterId) {  $searchUrl = "http://search.twitter.com/search.atom?q=".$searchText;  if(!empty($lastTwitterId)){    $searchUrl = $searchUrl."&since_id=".$lastTwitterId;  }  $twitterAtom = file_get_contents($searchUrl);  return $twitterAtom;  }


First, the search text is concatenated with the Twitter search base URL using the parameter q. If $lastTwitterId is not empty, it will be added to the search URL as the parameter since_id. The $lastTwitterId parameter will be empty on the first search, as there are no tweets loaded yet.

The PHP function file_get_contents is then called with the search URL passed in. file_get_contents supports URL input, which makes it very easy to load data from an external URL. The result is then returned to the Silverlight client. And that’s it: the PHP work is done. So easy!

Silverlight Twitter Client

Now that you have a service to load Twitter search data, you’re ready to create the Silverlight client. Start by creating a new Silverlight project in Visual Studio. For the purposes of this article I used Visual Studio 2010 and Silverlight 4 tools, but Silverlight 3 should also work (with Visual Studio 2008).

Follow the steps outlined in the previous article to create your Silverlight project; this time we’ll call it SilverlightPHPTwitter, as shown in Figure 1, “Creating a new Sliverlight project”.

Figure 1. Creating a new Sliverlight project

Creating a new Sliverlight project


Once you enter your filename, you can keep selecting the default settings until you see that your Silverlight project has been created. You’ll be presented with the MainPage.xaml file all ready for you to start adding code to load some tweets!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments