已阅读5页,还剩22页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
C H A P T E R 2 0Web ServicesThis chapter discusses some of the more applicable implementations of Web Servicestechnologies and shows you how to use PHP to start incorporating them into yourWeb application development strategy right now. To accomplish this goal withoutactually turning this chapter into a book unto itself, the discussion that follows isntintended to offer an in-depth introduction to the general concept, and advantages, ofWeb Services.Even if you have no prior experience with or knowledge of Web Services, hopefullyyoull find this chapter quite easy to comprehend. The intention here is to demonstratethe utility of Web Services through numerous practical demonstrations. Specifically, thefollowing topics are discussed:Why Web Services? For the uninitiated, this section very briefly touches upon thereasons for all of the work behind Web Services and how they change the landscapeof application development.Really Simple Syndication: The originators of the World Wide Web had little ideathat their accomplishments in this area would lead to what is certainly one of thegreatest technological leaps in the history of humankind. However, the extraordinarypopularity of the medium caused the capabilities of the original mechanisms tobe stretched in ways never intended by their creators. As a result, new methods forpublishing information over the Web have emerged and are starting to have as greatan impact on the way we retrieve and review data as did their predecessors. One suchtechnology is known as Really Simple Syndication, or RSS. This section introducesRSS and demonstrates how you can incorporate RSS feeds into your developmentacumen using a great tool called MagpieRSS.504 CHAPTER 20 WEB SERVICESSimpleXML: New to PHP 5, the SimpleXML extension offers a new and highlypractical methodology for parsing XML. This section introduces this new featureand offers several practical examples demonstrating its powerful and intuitivecapabilities.SOAP: The SOAP protocol plays an enormously important role in the implementationof Web Services. This section discusses its advantages and introducesPHPs SOAP extension, which was made available with the version 5 release.Why Web Services?Although the typical developer generally adheres to a loosely defined set of practices andtools, much as an artist generally works with a particular medium and style, he tendsto create software in the way he sees most fit. As such, it doesnt come as a surprisethat although many programs resemble one another in look and behavior, the similaritieslargely stop there. Numerous deficiencies arise as a result of this refusal tofollow generally accepted programming principles, with software being developed ata cost of maintainability, scalability, extensibility, and interoperability.This problem of interoperability has become even more pronounced over the pastfew years, given the incredible opportunities for cooperation that the Internet hasopened up to businesses around the world. However, fully exploiting an online businesspartnership often, if not always, involves some level of system integration. Thereinlies the problem: if the system designers never consider the possibility that they mightone day need to tightly integrate their application with another, how will they ever reallybe able to exploit the Internet to its fullest advantage? Indeed, this has been a subjectof considerable discussion almost from the onset of this new electronic age.Web Services technology is todays most promising solution to the interoperabilityproblem. Rather than offer up yet another interpretation of the definition of WebServices, heres an excellent interpretation provided in the W3Cs “Web ServicesArchitecture” document (/TR/ws-arch/):A Web service is a software system designed to support interoperable machineto-machine interaction over a network. It has an interface described in amachine-processable format (specifically WSDL). Other systems interact withthe Web service in a manner prescribed by its description using SOAP messages,typically conveyed using HTTP with an XML serialization in conjunction withother Web-related standards.CHAPTER 20 WEB SERVICES 505Some of these terms may be alien to the newcomer; not to worry, because theyreintroduced later in the chapter. What is important to keep in mind is that Web Servicesopen up endless possibilities to the enterprise, a sampling of which follows:Software as a service: Imagine building an e-commerce application that requiresa means for converting currency among various exchange rates. However, ratherthan take it upon yourself to devise some means for automatically scraping theFederal Reserve Banks Web page (/releases/) forthe daily released rate, you instead take advantage of its (hypothetical) Web Servicefor retrieving these values. The result is far more readable code, with much lesschance for error from presentational changes on the Web page.Significantly lessened Enterprise Application Integration (EAI) horrors: Developerscurrently are forced to devote enormous amounts of time to hackingtogether often complex solutions to integrate disparate applications. Contrastthis with connecting two Web Serviceenabled applications, in which the processis highly standardized and reusable no matter the language.Write once, reuse everywhere: Because Web Services offer platform-agnosticinterfaces to exposed application methods, they can be simultaneously used byapplications running on a variety of operating systems. For example, a Web Servicerunning on an e-commerce server might be used to keep the CEO abreast ofinventory numbers via both a Windows-based client application and a Perl scriptrunning on a Linux server that generates daily e-mails that are sent to the executiveteam.Ubiquitous access: Because Web Services typically travel over the HTTP protocol,firewalls can be bypassed because port 80 (and 443 for HTTPS) traffic is almostalways allowed. Although debate rages as to whether this is really prudent, for themoment it is indeed an appealing solution to the often difficult affair of firewallpenetration.Such capabilities are tantalizing to the developer. Believe it or not, as is demonstratedthroughout this chapter, you can actually begin taking advantage of Web Servicesright now.506 CHAPTER 20 WEB SERVICESUltimately, only one metric will determine the success of Web Services: acceptance.Interestingly, several global companies have already made quite a stir by offering WebServices application programming interfaces (APIs) to their treasured data stores. Amongthe most interesting offers include those provided by the online superstore A,Google, and Microsoft, stirring the imagination of the programming industry withtheir freely available standards-based Web Services. Since their respective releases, allthree implementations have sparked the imaginations of programmers worldwide, whohave gained valuable experience working with a well-designed Web Services architectureplugged into an enormous amount of data.Follow these links to learn more about these popular APIs: /webservices/ /more/ /mappoint/Really Simple SyndicationGiven that the entire concept of Web Services largely sprung out of the notion thatXML- and HTTP-driven applications would be harnessed to power the next generationof business-to-business applications, its rather ironic that the first widespreadimplementation of the Web Services technologies happened on the end-user level.RSS solves a number of problems that both Web developers and Web users havefaced for years.All of us can relate to the considerable amount of time consumed by our daily surfingritual. Most people have a stable of Web sites that they visit on a regular basisinsome cases, several times daily. For each site, the process is almost identical: visit theURL, weave around a sea of advertisements, navigate to the section of interest, andfinally actually read the news story. Repeat this process numerous times, and the nextthing you know, a fair amount of time has passed. Furthermore, given the highlytedious process, its easy to miss something of interest. In short, leave the process toa human and something is bound to get screwed up.CHAPTER 20 WEB SERVICES 507Developers face an entirely different set of problems. Once upon a time, attractingusers to your Web site involved spending enormous amounts of money on primetimecommercials and magazine layouts, and throwing lavish holiday galas. Then thenovelty wore off (and the cash disappeared) and those in charge of the Web sites wereforced to actually produce something substantial for their site visitors. Furthermore,they had to do so while working with the constraints of bandwidth limitations, themyriad of Web-enabled devices that sprung up, and an increasingly finicky (and timepressed)user. Enter RSS.RSS offers a formalized means for encapsulating a Web sites content within anXML-based structure, known as a feed. Its based on the premise that most site informationshares a similar format, regardless of topic. For example, although sports,weather, and theater are all vastly dissimilar topics, the news items published undereach would share a very similar structure, including a title, an author, a publicationdate, a URL, and a description. A typical RSS feed embodies all such attributes, andoften much more, forcing an adherence to a presentation-agnostic format that can inturn be retrieved, parsed, and formatted in any means acceptable to the end user,without actually having to visit the syndicating Web site. With just the feeds URL, theuser can store it, along with others if he likes, into a tool that is capable of retrievingand parsing the feed, allowing the user to do as he pleases with the information. Workingin this fashion, you can use RSS feeds to do the following: Browse the rendered feeds using a standalone RSS aggregator application. Examplesof popular aggregators include RSS Bandit (/),Straw (/projects/straw/), and SharpReader (/). A screenshot of RSS Bandit is shown in Figure 20-1. Subscribe to any of the numerous Web-based RSS aggregators and view thefeeds via a Web browser. Examples of popular online aggregators includeGoogle Reader (/reader/), NewsIsFree (/), and Bloglines (/). Retrieve and republish the syndicated feed as part of a third-party Web applicationor service. Later in this section, youll learn how this is accomplished usingthe MagpieRSS class library.508 CHAPTER 20 WEB SERVICESFigure 20-1. The RSS Bandit interfaceWHOS PUBLISHING RSS FEEDS?Believe it or not, RSS has actually officially been around since early 1999, and in previous incarnationssince 1996. However, like many emerging technologies, it remained a niche tool of the “techie”community, at least until recently. The emergence and growing popularity of news aggregationsites and tools has prompted an explosion in terms of the creation and publication of RSS feedsaround the Web. These days, you can find RSS feeds just about everywhere, including within theseprominent organizations: Yahoo! News: /rss/ The Christian Science Monitor: /rss/ CNET N: /CHAPTER 20 WEB SERVICES 509 BBC: http:/www.bbc.co.uk/syndication/ W: /wired/topheadlinesGiven the adoption of RSS in such circles, it isnt really a surprise that were hearing so muchabout this great technology these days.Understanding RSS SyntaxIf youre not familiar with the general syntax of an RSS feed, Listing 20-1 offers anexample, which will be used as input for the scripts that follow. Although a discussionof RSS syntax specifics is beyond the scope of this book, youll nonetheless find thestructure and tags to be quite intuitive (after all, thats why they call it Really SimpleSyndication).Listing 20-1. A Sample RSS Feed (blog.xml)Inside Open Source/Killer Firefox Tip #294/article/190/W. Jason GilmoreLike most of you, I spend bunches of time downloading largefiles from the Web, typically podcasts and PDF documentsBeginning Ubuntu Linux wins Linux Journal Award!/article/189/Keir ThomasWoo hoo! My book, Beginning Ubuntu Linux, has won an awardin the Linux Journal Editors Choice 2006 awards!More precisely510 CHAPTER 20 WEB SERVICESForms Validation with CakePHP/article/188/W. Jason GilmoreNeglecting to validate user input is akin to foregoingany defensivegameplan for containing the NFLs leading rusher. Chances aresooner or laterThis example doesnt take advantage of all available RSS elements. For instance,other feeds might contain elements describing the feeds update interval, language,and creator. However, for the purposes of the examples found in this chapter, itmakes sense to remove those components that have little bearing on instruction.Now that youre a bit more familiar with the purpose and advantages of RSS, youllnext learn how to use PHP to incorporate RSS into your own development strategy.Although there are numerous RSS tools written for the PHP language, one in particularoffers an amazingly effective solution for retrieving, parsing, and displaying feeds:MagpieRSS.Introducing MagpieRSSMagpieRSS (Magpie for short) is a powerful RSS parser written in PHP by Kellan Elliott-McCrea. Its freely available for download via / and isdistributed under the GPL license. Magpie offers developers an amazingly practicaland easy means for retrieving and rendering RSS feeds, as youll soon see. In addition,Magpie offers to users a number of cool features, including the following:Simplicity: Magpie gets the job done with a minimum of effort by the developer.For example, typing a few lines of code is all it takes to begin retrieving, parsing,and converting RSS feeds into an easily readable format.Nonvalidating: If the feed is well formed, Magpie will successfully parse it. Thismeans that it supports all tag sets found within the various RSS versions, as wellas your own custom tags.CHAPTER 20 WEB SERVICES 511Bandwidth-friendly: By default, Magpie caches feed contents for 60 minutes,cutting down on use of unnecessary bandwidth. Youre free to modify the defaultto fit caching preferences on a per-feed basis. If retrieval is requested after thecache has expired, Magpie will retrieve the feed only if it has been changed (bychecking the Last-Modified and ETag headers provided by the Web server). Inaddition, Magpie recognizes HTTPs Gzip content-negotiation ability whensupported.Installing MagpieLike most PHP classes, Magpie is as simple to install as placing the relevant files within adirectory that can later be referenced from a PHP script. The instructions for doingso follow:1. Download Magpie from /.2. Extract the package contents to a location convenient for inclusion from a PHPscript. For instance, consider placing third-party classes within an aptly nameddirectory located within the PHP_INSTALL_DIR/includes/ directory. Note thatyou can forgo the hassle of typing out the complete path to the Magpie directoryby adding its location to the include_path directive found in the php.ini file.3. Include the Magpie class (magpie.php) within your script:require(magpie/magpie.php);Thats it. Youre ready to begin using Magpie.How Magpie Parses a FeedMagpie parses a feed by placing it into an object consisting of four fields: channel,image, items, and textinput. In turn, channel is an array of associative arrays, whilethe remaining three are associative arrays. The following script retrieves the blog.xmlfeed, outputting it using the print_r() statement:512 CHAPTER 20 WEB SERVICESThis returns the following output (formatted for readability):Magpie_Feed Object (items = Array (0 = Array (title = Killer Firefox Tip #294title_detail = Array (type = textvalue = Killer Firefox Tip #294)link = /article/190/links = Array (0 = Array (rel = alternate href =/article/190/)author = W. Jason Gilmoredescription = Like most of you, I spend bunches of timedownloading large files from the Web,typically podcasts and PDF documents.)1 = Array (title = Beginning Ubuntu Linux wins Linux Journal Award!title_detail = Array (type = textvalue = Beginning Ubuntu Linux wins Linux Journal Award!)link = /article/189/links = Array (0 = Array (rel = alternate href = /article/189/)CHAPTER 20 WEB SERVICES 513author = Keir Thomasdescription = Woo hoo! My book, Beginning Ubuntu Linux, haswon an award in the Linux Journal Editors Choice2006 awards! More precisely.)2 = Array (title = Forms Validation with CakePHPtitle_detail = Array (type = textvalue = Forms Validation with CakePHP)link = /article/188/links = Array (0 = Array (rel = alternatehref = /article/188/)author = W. Jason Gilmoredescription = Neglecting to validate user input is akin to foregoingany defensive gameplan for containing the NFLsleading rusher. Chances are sooner or later.)feed = Array (title = Inside Open Sourcetitle_detail = Array (type = textvalue = Inside Open Source)link = /links = Array (0 = Array (rel = alternatehref = /)514 CHAPTER 20 WEB SERVICESfeed_type =feed_version =_na
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 深度解析(2026)《GBT 34211-2017铁矿石 高温荷重还原软熔滴落性能测定方法》
- 新型护理技术实操康复护理康复训练云计算支持课件
- 2026年万安第二中心幼儿园招聘备考题库有完整答案详解
- 2026年福州国企下属公办幼儿园公开招聘教职工人员42人备考题库及答案详解(易错题)
- 2026年春季学期青园梓枫小学教师招聘备考题库及答案详解(夺冠系列)
- 广州铁路职业技术学院2026年第一批引进急需专业人才10人备考题库及答案详解一套
- 2026年内江高新园区管理有限责任公司面向社会公开招聘工作人员的备考题库及答案详解(易错题)
- 2026年宁波和丰产业园(集团)有限公司招聘备考题库完整参考答案详解
- 2026年国家空间科学中心空间环境探测重点实验室空间环境探测载荷工程技术人员招聘备考题库及完整答案详解
- 2026年上海市同济口腔医院(同济大学附属口腔医院)实验技术员招聘备考题库及完整答案详解一套
- 福建省泉州市2022-2023学年高一上学期期末教学质量监测化学试题(含答案)
- 一级建造师机电工程管理与实务
- 英语book report简单范文(通用4篇)
- 船舶建造 监理
- 化学品安全技术说明书MSDS(洗车水)知识讲解
- 红楼梦英文版(杨宪益译)
- YY/T 1447-2016外科植入物植入材料磷灰石形成能力的体外评估
- GB/T 8331-2008离子交换树脂湿视密度测定方法
- GB/T 38658-20203.6 kV~40.5 kV交流金属封闭开关设备和控制设备型式试验有效性的延伸导则
- 美英报刊阅读教程课件
- 幼儿园绘本故事:《十二生肖》 课件
评论
0/150
提交评论