Building a Complete Web Searching Class with Yahoo Web Services and PHP 5

Welcome to the final part of the series “Using Yahoo! Web Services with PHP 5.” As the title claims, this series walks you through the basic concepts surrounding the correct utilization of the most relevant web search services provided by Yahoo! and puts the corresponding theory into practice by utilizing both procedural and object-oriented approaches.

As you possibly know, Yahoo! has recently released a thorough set of Web Service APIs that can be easily consumed by using some popular server-side programming languages, including my favorite one, PHP. If you’re interested in learning how to implement these useful services directly from your own PHP 5 applications, then look no further, because you’ve come to the right place.

Provided that you already went through all of the previous articles of the series, I could say that at this point you should have a pretty solid background in consuming the Yahoo! Web Search Services by way of some procedural PHP functions and a few straightforward classes as well.

As you saw for yourself in the course of the preceding articles, implementing a particular Yahoo! Web Search Service with PHP 5 is a relatively straightforward process, since it only requires an intermediate background in fetching file contents and processing multidimensional arrays using a few common PHP functions.

However, there’s one particular thing that you’ll certainly recall from the last tutorial: on that occasion I showed you how to utilize the respective Yahoo! traditional and video search services via two modular PHP 5 classes, which implemented some basic methods for performing the searches.

Of course, it’s fair to mention here that the signatures corresponding to all these classes were very similar to each other. This naturally implies that it’s possible to use inheritance to create one base class, and then derive some sub classes according to the web service that needs to be implemented in a specific case. Sounds pretty logical, right?

So, this last installment of the series will be entirely focused on demonstrating how Inheritance can be used in a helpful way to build a set of child classes that will come in handy for consuming a specific Yahoo! Search Service.

Now that you know the subject of this tutorial, it’s time to learn how these web searching classes will be created with PHP 5. Ready to start? Let’s go!

{mospagebreak title=Defining an image searching class in PHP 5}

I need to show you something before I teach you how to use Inheritance to build some child classes that will concretely implement each of the Yahoo! Web Search Services discussed in the previous articles of the series. Below you will see the corresponding definition of a simple class that is tasked with consuming the Yahoo Image Search Service, which was left undefined in the last tutorial.

Here’s the signature of this brand new PHP class, which is responsible for performing image searches using the corresponding Yahoo API. Take a look at it, please:


// example using Yahoo! Image Search Service – results are displayed in a basic (X)HTML format utilizing a class


// define ‘ImageSearchService’ class

class ImageSearchService{

private $requestPath=’http://search.yahooapis.com/
ImageSearchService/V1/imageSearch?appid=Your-AP-ID';

private $query=’madonna';

private $numResults=10;

private $output=”;

public function __construct(){}

// set search query

public function setQuery($query){

if(!$query){

throw new Exception(‘Invalid search query!’);

}

$this->query=urlencode($query);

}

// set number of search results

public function setNumResults($numResults){

if(!$numResults||!is_int($numResults)||$numResults>50){

throw new Exception(‘Invalid number of results!’);

}

$this->numResults=$numResults;

}

// perform web search and get search results

public function getSearchResults(){

if(!$results=file_get_contents($this->requestPath.’&query=’
.$this->query.’&results=’.$this->numResults.’&output=php’)){

throw new Exception(‘Error requesting Yahoo! Web service’);

}

$results=unserialize($results);

foreach($results[ResultSet][Result] as $result){

$this->output.='<h2>’.$result[Title].'</h2><p>’.$result
[Summary].'</p><p><img src="’.$result[Thumbnail][Url].
‘" width="’.$result[Thumbnail][Width].’" height="’.$result
[Thumbnail][Height].’" /></p><a href="’.$result[Url].’">’.
$result[Url].'</a>';

}

return $this->output;

}

}


As you can see, the definition of the above “ImageSearchService” class looks very similar to the ones that I defined in the previous tutorial, which were aimed at working with the respective Yahoo traditional and image web searches. In this case, I built this class so it can perform image searches very easily, which is certainly a process that’s clearly demonstrated by the following hands-on example:


try{

// create new instance of ‘ImageSearchService’ class

$is=new ImageSearchService();

// set search query

$is->setQuery(‘Dido’);

// set number of search results

$is->setNumResults(10);

// display search results

echo $is->getSearchResults();

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


// displays the following

dido_270.jpe


http://fanwebdido.wz.cz/fotogalerie/dido_270.jpe

Dido-Life_For_Rent-Frontal.jpg


Enrique Iglesias – 7 50 cent-Get rich or die.. Dido – Life for rent
Safri duo – 3.0 (new)


http://www.coveralia.com/audio/d/Dido-Life_For_Rent-
Frontal.jpg

Dido_kontje.jpg


http://xs45.xs.to/pics/05365/Dido_kontje.jpg

dido_1.jpg


http://peoples.ru/art/music/pop/dido/dido_1.jpg

Dido.jpg


http://biografie.leonardo.it/img/bio/d/Dido.jpg

dido.jpg


Pop chanteuse Dido entered London’s Guildhall School of
Music at age six , and had mastered the piano, the violin
and the recorder by the time she was 10. After touring with a


http://www.grabow.biz/images/dido.jpg

dido.jpg


dezembro 25, 2005 Parabans 1954 – Annie Lennox , cantora
1971 – Dido , cantora Publicado por nelourenco à s


http://atuleirus.weblog.com.pt/arquivo/dido.jpg

dido128.jpg


Dido: ‘I camped out the night before Wham! The Final’.
Photo: Pete Millson


http://image.guardian.co.uk/sys-images/Guardian/Pix/arts/
2003/10/02/dido128.jpg

Dido2654.jpg


http://www.sirensofsong.com/Dido/images/Dido2654.jpg

INT-Dido.jpg


Dido Born Florian Cloud de Bounevialle Armstrong, on the
25th of December 1971, in England, Dido is the sister of
Faithless mastermind and leading UK dance music producer,
Rollo. She


http://www.annecarlini.com/images/exclusive/interviews/INT-Dido.jpg


Undoubtedly, consuming the Yahoo! Image Search Service by using the class that I built earlier is not only a no-brainer process that can be tackled with minor effort, but a fun experience! Okay, I have to admit that it actually isn’t so fun for some, but keep in mind that I have to market this class to you somehow.

Well, I assume at this time that the previous example should give you a clear idea of how to build a PHP class that utilizes the Yahoo! Image Search Service in a useful fashion. So, what’s the next step?

In accordance with the concepts that I deployed in the beginning, in the next section I’m going to teach you how to use Inheritance to create different subclasses. Each of them will be focused on consuming a specific Yahoo! Web service. In this manner, we will develop a more efficient object-oriented approach that will work with the services in question.

To find out how these subclasses will be built, please jump ahead and read the next few lines.

{mospagebreak title=Using Inheritance to work with different Yahoo! Web Services}

Since the web service classes that you learned before are very similar to each other, it’s preferable to take a more efficient approach and build a base class that encapsulates as much common functionality as possible. Next, derive some subclasses that implement (or eventually) override some of the parent’s method in order to use a specific Yahoo! Web Service.

Of course, to do so I have to appeal to Inheritance, but first let me show you the signature of this base web searching class. It is as follows:


// define abstract ‘SearchService’ class


abstract class SearchService{

protected $requestPath;

protected $query;

protected $numResults;

protected $output;

public function __construct(){

$this->query=’madonna';

$this->numResults=10;

$this->output=”;

}

// set search query

public function setQuery($query){

if(!$query){

throw new Exception(‘Invalid search query!’);

}

$this->query=urlencode($query);

}

// set number of search results

public function setNumResults($numResults){

if(!$numResults||!is_int($numResults)||$numResults>50){

throw new Exception(‘Invalid number of results!’);

}

$this->numResults=$numResults;

}

// define a generic method to perform web search and get search results

public function getSearchResults(){}

}


As you can see, in this case I simply defined the previous “SearchService” class abstract, since I don’t want it to be instantiated later on. However, this class also defines one generic “getSearchResults()” method (aside from the corresponding constructor, of course), which needs to be implemented in a concrete way by all the subclasses derived from this parent to use a specific Yahoo! Web Search Service.

Defining the previous classes this way permits us to build some child classes, which will be responsible for consuming a concrete Yahoo! Web service. Undoubtedly, this is a clear example of how useful Inheritance can be in a real-world situation.

All in all, at this point I’m pretty sure that you understand how the prior “SearchService” class was built, so it’s an appropriate moment to learn how the respective subclasses will be derived from this parent.

Indeed, this process will be quite interesting, so to learn more, please click on the link below and read the following section.

{mospagebreak title=Consuming specific Yahoo! Web Search Services}

As I discussed in the last section, in this particular case I’m going to use the benefits of Inheritance to derive three subclasses from the “WebService” parent that you saw earlier. As you might have guessed at this point, each of these will concretely implement the generic “getSearchResults()” declared in the base class, something that certainly will come in handy for consuming a specific Yahoo! Web Search Service.

Still with me? All right, now take a deep breath, relax, and have a look at the signatures of the following subclasses. Each of them works with a different web search service:


// derive ‘WebSearchService’ class from parent ‘SearchService’

class WebSearchService extends SearchService{

public function __construct(){

parent::__construct();

$this->requestPath=’http://api.search.yahoo.com/
WebSearchService/V1/webSearch?appid=Your-AP-ID';

}

// implement concretely ‘getSearchResults’ method

public function getSearchResults(){

if(!$results=file_get_contents($this->requestPath.’&query=
‘.$this->query.’&results=’.$this->numResults.’&output=php’)){

throw new Exception(‘Error requesting Yahoo! Web service’);

}

$results=unserialize($results);

foreach($results[ResultSet][Result] as $result){

$this->output.='<h2>’.$result[Title].'</h2><p>’.$result
[Summary].'</p><a href="’.$result[Url].’">’.$result[Url].'</a>';

}

return $this->output;

}

}



// derive ‘VideoSearchService’ class from parent ‘SearchService’


class VideoSearchService extends SearchService{

public function __construct(){

parent::__construct();

$this->requestPath=’http://search.yahooapis.com/
VideoSearchService/V1/videoSearch?appid=Your-AP-ID';

}

// implement concretely ‘getSearchResults’ method

public function getSearchResults(){

if(!$results=file_get_contents($this->requestPath.’&query=’
.$this->query.’&results=’.$this->numResults.’&output=php’)){

throw new Exception(‘Error requesting Yahoo! Web service’);

}

$results=unserialize($results);

foreach($results[ResultSet][Result] as $result){

$this->output.='<h2>’.$result[Title].'</h2><p>’.$result
[Summary].'</p><p><img src="’.$result[Thumbnail][Url].
‘" width="’.$result[Thumbnail][Width].’" height="’.$result
[Thumbnail][Height].’" /></p><a href="’.$result[Url].’">’.
$result[Url].'</a>';

}

return $this->output;

}

}


// derive ‘ImageSearchService’ class from parent ‘SearchService’


class ImageSearchService extends SearchService{

public function __construct(){

parent::__construct();

$this->requestPath=’http://search.yahooapis.com/
ImageSearchService/V1/imageSearch?appid=Your-AP-ID';

}

// implement concretely ‘getSearchResults’ method

public function getSearchResults(){

if(!$results=file_get_contents($this->requestPath.’&query=’.
$this->query.’&results=’.$this->numResults.’&output=php’)){

throw new Exception(‘Error requesting Yahoo! Web service’);

}

$results=unserialize($results);

foreach($results[ResultSet][Result] as $result){

$this->output.='<h2>’.$result[Title].'</h2><p>’.$result[Summary].
‘</p><p><img src="’.$result[Thumbnail][Url].’" width="’.$result
[Thumbnail][Width].’" height="’.$result[Thumbnail][Height].’" />
</p><a href="’.$result[Url].’">’.$result[Url].'</a>';

}

return $this->output;

}

}


You’ll have to agree that building some web searching classes that consume specific Yahoo! Web Services from a base class is a very comprehensive process that can be performed with minor difficulties. As you can see, in this case I derived three different child classes, called “WebSearchService,” “VideoSearchService,” and “ImageSearchService” respectively. And not surprisingly, each of them is focused on consuming a specific Yahoo! Web Service.

Besides, it’s worthwhile to note here that these subclasses concretely implement the same generic “getSearchResults()” method declared in the parent, which implies that any instance of them will certainly be a polymorphic object too.

Well, now that you’ve grasped the logic that stands behind these web search subclasses, you may want to see how they work. So considering this possibility, below I included some practical examples that show these classes in action. Here they are:

// example on using “Yahoo Web Search Service


try{

// create new instance of ‘WebSearchService’ class

$ws=new WebSearchService();

// set search query

$ws->setQuery(‘Devshed.com’);

// set number of search results

$ws->setNumResults(15);

// display search results

echo $ws->getSearchResults();

 

}

catch(Exception $e){

echo $e->getMessage();

exit();

}



// example on using “Yahoo Video Search Service


try{

// create new instance of ‘VideoSearchService’ class

$vs=new VideoSearchService();

// set search query

$vs->setQuery(‘dido’);

// set number of search results

$vs->setNumResults(15);

// display search results

echo $vs->getSearchResults();

 

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


// example on using “Yahoo Image Search Service


try{

// create new instance of ‘ImageSearchService’ class

$is=new ImageSearchService();

// set search query

$is->setQuery(‘dido’);

// set number of search results

$is->setNumResults(15);

// display search results

echo $is->getSearchResults();

 

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


True to form, the above three examples show in a nutshell how each of the subclasses that I built before can be used to easily consume a specific Yahoo! Web Search Service. Also, for obvious reasons, I’ve not included the pertinent results produced by each of these examples, but at this stage you should have a very clear idea of how to incorporate the previous web searching classes (or a modified version of them) into your own PHP applications.

Final thoughts

It’s hard to believe, but this is the end of the series. Nevertheless, I hope the overall experience has been pretty instructive, since in these tutorials you learned how to implement the most relevant web services provided by Yahoo! by using both procedural and object-oriented approaches in PHP 5.

As you know, the web is becoming more and more dynamic each day, so if you want to add an extra “touch” to your PHP 5 applications, you may want to consider consuming the cool set of Yahoo! Web Services.

See you in the next PHP development tutorial!

[gp-comments width="770" linklove="off" ]

chat