Article

Mash Up Your Music with the Zend Framework

Page: 1 2 3 Next

Declaring Filters and Validator Rules

In order to use the filter input class, we need to declare our filters and validators as arrays. Let's take a look at our first bit of code from our demo application:

<?php  
$filters = array(  
 'artist' => array(  
   'StripTags',  
   'StringTrim'  
 )  
);  
 
$validators = array(  
 'artist'  => array(  
   'Alnum',  
 )  
);  
?>

In the above example, we're using a filter on the field artist to remove tags and trim whitespace from either end of the string. We've also created a validator for the artist field to check that it contains only alphabetical or numerical characters.

Filters and validators can be applied one at a time, as we've done here, but it's also possible to chain them together...

Chaining

Sorry to disappoint you -- we're not talking about anything kinky here. Chaining refers to executing filters and/or validators one after another, each using the outputted value of the previous filter. This functionality in fact occurs by default. But, as we'll see later, it can be switched off when you're performing validation. In the above code, any HTML markup or PHP code is removed from the field artist, then the surrounding whitespace is removed.

For example, the string <strong> Hello World </strong> would be converted to "Hello World".

Creating a Processor for the Filters and Validators

Once we've declared our filters and validators, the next step is to use them to process our data. In the demo, we make use of the super global variable $_GET to retrieve all the query string input, like so:

$input = new Zend_Filter_Input($Filters, $Validators, $_GET);

Getting Invalid, Missing or Unknown Fields

The framework provides us with three methods for checking for invalid, missing, or unknown data. Each method returns a Boolean value:

  • hasInvalid - returns true if the data has not passed the validation checks
  • hasMissing - data specified to be present by the metacommand 'presence' => 'required' is missing (More on this later.)
  • hasUnknown - fields that are not specified for validation, but are included in the input data

In our demo app, we'll use hasInvalid and hasMissing as simple checks that our request has at least returned something useful. We can then get further information on the erroneous data using any of the following four methods:

  • getInvalid - Get information on any invalid data.
  • getMissing - Get information on any missing data.
  • getUnknown - Get information on any unexpected data.
  • getMessages - Get information on any invalid and missing data.

Each of these methods returns an array in this format:

Array  
(  
   [field] => Array  
       (  
           [0] => Error message  
       )  
)

To keep things simple, we'll use getMessages to print out any error messages:

<?php  
if ($input->hasInvalid() || $input->hasMissing()) {  
 print_r($input->getMessages());  
}  
?>

Getting at Our Data

Now that we've checked the data, it's time to retrieve it. For the purposes of our demo, we'll use the magic accessor to retrieve the HTML-escaped output for the field artist:

echo $input->artist;

It's also possible to use the getEscaped and getUnescaped methods to retrieve data that's escaped or unescaped, respectively.

There's a lot more that you can do to take control of your filters and validators with the Zend_Filter_Input component, including using metacommands and creating your own filters. To learn more, check out the manual.

Next, we'll take a look at web services and how to implement them.

Audioscrobbler

The Zend_Service_Audioscrobbler component provides a simple way to access the REST web service available from Audioscrobbler.com (Last.fm). This service gives us access to:

  • users
  • artists
  • albums
  • tracks
  • tags
  • groups
  • forums

For our demo application, we'll retrieve the top ten albums for a given artist, and display them with a link to Audioscrobbler.

First, we need to load and instantiate the Zend_Service_Audioscrobbler class:

Zend_Loader::loadClass('Zend_Service_Audioscrobbler');  
$Audioscrobbler = new Zend_Service_Audioscrobbler();

Next, we specify the artist that we want to retrieve information for, in this case, The Rolling Stones.

Don't forget to urlencode() the name, as Audioscrobbler uses the artist's name in the URL of the XML data file that it creates.

Let's specify the artist:

$Audioscrobbler->set('artist', urlencode('The Rolling Stones'));  
$results = $Audioscrobbler->artistGetTopAlbums());

Now that we have some data, we'll loop through the result set and print the album name, linking it back to its page on Audioscrobbler.com:

foreach ($results as $info) {  
 echo '<a href="' . $info->url . '">' . $info->name. '</a><br />';  
}

And that's all there is to it. Easy, huh?

Flickr

The Flickr web service follows much the same pattern as Audioscrobbler. There are however, a few more things to consider, including:

  • the license under which the image is made available
  • crediting the image owner

Licensing Images

There are six different licenses under which an image may be made available on Flickr. The "all rights reserved" images should not be republished on another site unless you are the owner, or you have permission from the owner. The rest of the licenses are variations on the Creative Commons license, and dictate specific usage that's acceptable for each image covered by that license:

Load 'em Up

Again, we first load the appropriate class and instantiate it with our API key:

Zend_Loader::loadClass('Zend_Service_Flickr');  
$flickr = new Zend_Service_Flickr('<- YOUR API KEY HERE ->');

Searching for Images

Flickr provides the ability to search for images either by tag or user. For our demo, we'll use the artist name as the tag for our search. We're also going to:

  • limit the results to eight images per page
  • display only the first page of results
  • only use images that are licensed under licences 1, 2, 3, 4, 5 or 6 (see above)

Here's how we would perform our Flickr search for those classic rockers that just keep on keeping on:

$options = array(  
 'per_page' => 8,  
 'page'=> 1,  
 'license' => '1, 2, 3, 4, 5, 6'  
);  
$results = $flickr->tagSearch('The Rolling Stones', $options);

There are further options to refine your search -- see the documentation for more details.

Now we (hopefully) have some results from our image search. You can check the number of returned results with any of the following functions:

  • Zend_Service_Flickr_ResultSet::totalResultsAvailable - returns the total number of images available for the current search terms
  • Zend_Service_Flickr_ResultSet::totalResultsReturned - returns the total number of images returned by the last search
  • Zend_Service_Flickr_ResultSet::firstResultPosition - returns the position of the most recently returned set of images, relative to the entire result set
  • Zend_Service_Flickr_ResultSet::totalResults() - returns the total number of images in the result set

Information is available for each result image, including the image ID, the ID of the image owner, the date the image was taken, whether the image is public, and much, much more. You can also access up to six different versions of an image:

  • Square - 75x75-pixel thumbnail
  • Thumbnail - 100-pixel thumbnail
  • Small - 240-pixel version of the image
  • Medium - 500-pixel version of the image
  • Large - 640-pixel version of the image
  • Original - the original image

Additionally, for each version of the image, you can access four properties:

  • uri - the URI for the original image
  • clickUri - link to the Flickr page of the image
  • width - the width of the Image in pixels
  • height - the height of the Image in pixels

For more information on the image details that are available to you, read the Zend_Service_Flickr documentation.

Enough theory, already -- let's add some Flickr photos to our mashup!

The following code sample will loop through the results of a search and, if more than one image is available (and it's public), display a square thumbnail of the image, with a link to the original image on Flickr:

$results = $Flickr->tagSearch($Artist, $FlickrOptions);  
if($results->totalResultsAvailable > 0) {  
 foreach ($results as $result){  
   if (isset($result->Square) && $result->ispublic =='1') {  
     $FlickResults .= '<a href="http://www.flickr.com/photos/'  
            + $result->owner.'/'.$result->id.'/"><img src="'  
            + $result->Square->uri.'" alt="'  
            + $HTMLFilter->filter($result->title).'  
            + " title="Picture from: '  
            + $HTMLFilter->filter($result->ownername)  
            +' at Flickr" /></a>'."\n";  
   }  
 }  
}  
else {  
 // no results found  
 $FlickResults .= 'No Images Found';  
}

Note how we get the individual image's properties (in this case the clickUri):

 $result->Square->clickUri

If we wanted to display the full, original image, we'd use:

  $result->Original->clickUri

That's a quick and dirty way to search for and access information on images at Flickr. Next up, we'll take a look at searching Yahoo News.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Follow SitePoint on...