PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to PHP Subscribe to Newsletters

Programming eBay Web Services with PHP 5 and Services_Ebay
Pages: 1, 2

Beautifying

Of course, that's not a very visually appealing display, but you can fix this problem with only a little bit of code:

require_once 'Services/Ebay/Model/Item.php';

class prettyItem extends Services_Ebay_Model_Item {
	public function __toString() {
		$title = $this->Title;
		$img   = $this->ItemProperties['GalleryURL'];
		$price = $this->LocalizedCurrentPrice;
		$link  = $this->Link;
		$time  = $this->EndTime;
		$bids  = $this->BidCount;
	
		// skip items without a gallery picture
		if (empty($img)) { return ''; }
		
		return <<<_HTML_
<div style="clear:left; width: 450px; padding:5px; margin:5px; background:#ddd;">
    <a href="$link"><image src="$img" 
      alt="$title" align="left" height="77" width="77" /></a>
    <b>$title</b><br/>
    Current Price: $price<br/>
    Number of Bids: $bids<br/>
    Ending Time: $time<br />
</div>
_HTML_;
	}
}

Services_Ebay::useModelClass('Item', 'prettyItem');

Services_Ebay uses a series of "model classes" to handle the dirty work of abstracting away the details behind the individual API calls. When GSR returns a list of eBay items, Services_Ebay instantiates Item models for each listing. Even better, it allows you to override the model to add or redefine methods to fix your application needs.

In this case, you're modifying the Item model's __toString() method to update the default display to a more attractive one.

First, you need to load the class, Services_Ebay_Model_Item, located inside the Models directory in Item.php. Once it's loaded, you can subclass it using the standard PHP extends syntax. In this example, the child class is prettyItem.

Inside of prettyItem::__toString(), a set of lines combines Item properties--including the title, price, and link--into a set of HTML elements.

The final step is to tell Services_Ebay to substitute your new model class for the default one. To do this, call the Services_Ebay::useModelClass() method. The first value is the model name; the second is the name of the replacement class.

Now, when you print out items, you'll have an entirely new picture:

	foreach ($items as $item) {
		echo $item;
	}

A new list of search results
Figure 2. A new list of search results

Notice that you didn't need to modify any of the logic for cycling through the items or for printing them out.

Introspecting

Besides creating an iterable list of items, GSR returns additional information about your search. For instance, while GSR returns a maximum of 100 items per call, it does allow you to "paginate" your request. This allows you to make one request for items 1-100, a second for 101-200, and so on.

In order to do this, however, you need to know the total number of potential results. This is available as an object property:

print $items->GrandTotal;
1153

Alternatively, you can use array syntax if you prefer:

print $items['GrandTotal'];
1153

These bits of syntactical sugar again use new PHP 5 features: the accessor method, __get(), and SPL's ArrayAccess interface, respectively.

To access all the properties at once, retrieve them using the toArray() method:

print_r($items->toArray());

Array
(
    [Count] => 100
    [HasMoreItems] => 1
    [GrandTotal] => 1155
    [PageNumber] => 1
)

This method exposes everything: the count of the items returned, whether there are any more items to fetch, the total number of available items, and the "page number" within the search results.

The ability to call methods on $items is one of the advantages of using an iterable object instead of an array. With an array, you're just holding a set of individual items. Now, you can provide collection of items, packaged more tightly as parts of a whole.

On the flip side, it's useful to know what parameters GSR takes. Earlier on, I said that the first argument is the search string, but GSR actually takes up to five parameters. You could read the documentation or flip through the code, but Services_Ebay wants to make things really easy.

Therefore, every API call has a describeCall() method, which lets you retrieve a method's parameters from within the code itself:

$call = Services_Ebay::loadAPICall('GetSearchResults');
$call->describeCall();

API-Call : GetSearchResults

Parameters (max. 5)
 Query(no default value)
 SearchInDescription(no default value)
 Skip(no default value)
 MaxResults(no default value)
 Category(no default value)

API Documentation : http://developer.ebay.com/DevZone/docs/API_Doc/
Functions/GetSearchResults/GetSearchResultsLogic.htm

As you see, describeCall() returns three pieces of information:

  • the name of the API call
  • a list of all parameters and their default values, if any
  • a link to the eBay API documentation for that call

This not only lets you figure out how Services_Ebay has modeled a call but also points you directly to the official eBay documentation, so you can read the definitive reference.

Surprisingly, even describeCall() uses a new PHP 5 feature: reflection. PHP 5's reflection classes let you retrieve information about classes and functions in a programmatic fashion. In this example, the documentation URL actually comes from a specially formatted comment above the class that phpDocumentor, an auto-documentation tool for PHP, can read. With PHP 5 you can extract these comments without reading and parsing the class file yourself by instantiating a class and invoking a single method, getDocComment().

Conclusion

You've just seen how easy it is to write a eBay web services search application in PHP with the help of Services_Ebay. Services_Ebay uses much of the power of PHP 5: the whole spectrum of the new object model, the rewritten XML and XSL extensions, iterators and SPL, reflection, and exceptions. These components combine to create a kick-ass tool that PHP 4 can't replicate without lots of work, if at all.

Furthermore, the eBay API is not restricted to read-only calls, such as searching for and viewing listings. You can do almost everything through the API, including listing items, giving and checking feedback, managing eBay Stores, retrieving data from your My eBay page, and setting preferences. Services_Ebay supports most of these calls today and is quickly adding the rest.

As a result, now's a great time for PHP developers to start exploring the power of the eBay API.

Adam Trachtenberg is the manager of technical evangelism for eBay and is the author of two O'Reilly books, "Upgrading to PHP 5" and "PHP Cookbook." In February he will be speaking at Web Services Edge 2005 on "Developing E-Commerce Applications with Web Services" and at the O'Reilly booth at LinuxWorld on "Writing eBay Web Services Applications with PHP 5."


Return to the PHP DevCenter.


Have a question about the eBay API or the advanced features Adam's demonstrated? Ask him here.
You must be logged in to the O'Reilly Network to post a talkback.
Post Comment
Full Threads Oldest First

Showing messages 1 through 2 of 2.

  • How to add item using ebay web services
    2006-07-06 01:12:18  M-Shahid [Reply | View]

    Hi All,
    I am trying to add item for many days but still I am heaving problems. I am using nusoap in my php application.
    My php code is as below.[/pre]<?php
    require_once('nusoap.php');
    $param = array('Currency' => 'USD',
    'Country' => 'US',
    'BuyItNowPrice' => '5.5',
    'eBayAuthToken' => 'AgAAAA**AQAAAA**aAAAAA**17tgRA**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wJnY+lDZWCpw2dj6x9nY+seQ**gmkAAA**AAMAAA**jEiD1/ki0UiT+5IW2yny0K3pteXHWd8dfWoBvaR10jYRL3Pe9QDXZhENV/TgDUBnJBpA3eaFXoBcHgSBFGENu1p5NPI/XEI1EC6qaef7YhoozlqkoegA+uzpg83EZNWggomERenpBRbjmFAA/joVdn6WFpK5F+tBOKfAgK/cgf+dWWwQ85hjFRE4x2e4Rvi4SPkxRDsD5HZcfxkD14T7FhVTkeraaKm9kEOnqeTedWfT7R1ZdDyKwhX190tOKQqiEcFWxHLjuy9sGgKZI1qF6o+rjKZBo/nXHx2JGDVC5oLyAnMwlvuU5MkonOSMC6XGEAt7YCMS6A7ODNATfFB/LUY6Hwal/BAkyCdXKUNnYrPlELCyvmqZyeI/gkVoxU9dFF6UuJyX+Tek6vdODGCuJHHn2NDUXB54J5Um2QP48K5oS0jw1h+GTLwoLaA9FaX0IQBdleAw/CJy8SPd7CM0tOkyQ84i2l25FOYJ5FUqaReLLJhv3sGEYxU9lmzhIWj98yWcqprY7LnECU2CRSsWRygElh/U6ZcR4uRj6pnfZwmWON7sjRRsMJLoGMnlg3OfOQadVFYp5JfQ2XfxtkRas3uCcOhTpmG8EcUx28Xbf/h/QQhHNgdxDwmPYZKwzyIziLOjY6lPFVebT+EPadSqEYrigqul9rm/IyZQ9gtN/M02al+CPEOdtvzizMgr221+MjaipGW+zviEnOBPsgR9kF8SRFw9dywuHT1P8Zm2jbC2a6qY0ln/CQepIpcl/Pix',
    'ListingDuration' => 'Days_7',
    'Location' => 'San Jose, CA',
    'PaymentMethods' => 'PayPal',
    'PayPalEmailAddress' => 'abc@abc.com',
    'CategoryID' => '307',
    'RegionID' => '0',
    'StartPrice' => '0.55',
    'X-EBAY-API-COMPATIBILITY-LEVEL:' => '433',
    'X-EBAY-API-DEV-NAME:' => 'D79DE8FO8RE3125HY55FD51J866FX2',
    'X-EBAY-API-APP-NAME:' => 'SURENAMESIS821U3DX31536MUA3J71',
    'X-EBAY-API-CERT-NAME:' => 'E7D94KERMM6$6PX1NZ413-J6591DJL',
    'X-EBAY-API-SITEID:' => '0',
    'X-EBAY-API-CALL-NAME:' => 'AddItem',
    'Title' => 'Pink Floyd Dark Side of the Moon CD'
    );
    $client = new soapclient('https://api.sandbox.ebay.com/wsapi?callname=AddItem&siteid=0&version=450');


    $response = $client->call('AddItem',$param);

    if ($client->fault) {
    echo "FAULT: Code: {$client->faultcode}";
    echo "String: {$client->faultstring}";
    } else {
    echo "$" . $response;
    echo 'Request
    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    ';
    echo 'Response
    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    ';
    } ?>
    When I execute the script above the following error message display on my browser.
    FAULT:
    Code: soapenv:Server.userException
    String: org.xml.sax.SAXParseException: Element or attribute do not match QName production: QName::=(NCName':')?NCName.
    Please help me that where the actual problem is reside. I heave study AddItem manul also.
    Sorry for bad English,
    Regards:
    Shahid
  • Steve Mallett photo -a ?
    2005-11-08 12:37:39  Steve Mallett | O'Reilly Blogger [Reply | View]

    installing using the method described gives me "Release for 'services_ebay' dependency 'XML_Serializer' has state 'beta', requires 'stable'
    upgrade failed"


Tagged Articles

Post to del.icio.us

This article has been tagged:

ebay

Articles that share the tag ebay:

Programming eBay Web Services with PHP 5 and Services_Ebay (32 tags)

How eBay Uses Metadata to Enhance Its Web Services (17 tags)

View All

php

Articles that share the tag php:

Understanding MVC in PHP (477 tags)

The PHP Scalability Myth (123 tags)

The Dynamic Duo of PEAR::DB and Smarty (53 tags)

PHP Form Handling (43 tags)

Very Dynamic Web Interfaces (39 tags)

View All

webservices

Articles that share the tag webservices:

How to Create a REST Protocol (74 tags)

The REST of the Web (32 tags)

Implementing REST Web Services: Best Practices and Guidelines (31 tags)

Yahoo! Web Services (27 tags)

An Introduction to Service-Oriented Architecture from a Java Developer Perspective (27 tags)

View All

api

Articles that share the tag api:

Introducing del.icio.us (68 tags)

Hacking Maps with the Google Maps API (61 tags)

The Atom API (56 tags)

Dreaming of an Atom Store: A Database for the Web (32 tags)

The New Bloglines Web Services (30 tags)

View All

pear

Articles that share the tag pear:

The Dynamic Duo of PEAR::DB and Smarty (37 tags)

Programming eBay Web Services with PHP 5 and Services_Ebay (12 tags)

Three-Tier Development with PHP 5 (6 tags)

PHP's PEAR on Mac OS X (6 tags)

Caching PHP Programs with PEAR (6 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com