jojo's blog--快乐忧伤都与你同在
为梦想而来,为自由而生。 性情若水,风起水兴,风息水止,故时而激荡,时又清平……
posts - 11,  comments - 30,  trackbacks - 0
Long weekends reduce brain cells to jelly.  Worked on a few things over the weekend, nothing really to report except write down this simple example.

The next book has far too many XML chapters in it, or at least it seems that way at the moment.  I had a good anti-WS-bloat rant in Amsterdam recently.  In a nutshell: most of the web services stack is bloatware that doesn't get used for most applications.  90% of the time you can get away with knowing no SOAP, WSDL, or any of that stuff.  You can just use REST - Representational State Transfer.  This is basically an HTTP GET request with parameters, and in return you get an XML document, in other words XML over HTTP.   It works very nicely and is simple.  I was trying to explain this to somebody here at work, so I wrote a very basic REST server/client pair in PHP in five minutes to demonstrate.  Here's the code, which is doubled in size due to comments.

REST server for imaginary stock price lookup

restserver.php


 1 <?php
 2 
 3   // check which stock we want to look up
 4   $stock = $_GET['stock'];
 5 
 6   // look up the stock
 7   $price = lookup($stock);
 8 
 9   // format stock quote as XML
10   $string = "<stockquote><stockprice>$price</stockprice></stockquote>";
11 
12   // make it into a proper XML document with header etc
13   $xml = simplexml_load_string($string);
14 
15   // send an XML mime header
16   header("Content-type: text/xml");
17 
18   // output correctly formatted XML
19   echo $xml->asXML();
20 
21 // that's the end of the main code, function below is just a stub
22 
23   function lookup($s)
24   {
25     // all stocks are worth $1 for this basic example
26     // but you would look it up in a database if you had one
27     return 1;
28   }
29 

REST client demo

restclient.php


 1 <?php
 2 
 3 // query the REST server and load the returned XML as a PHP object
 4 // note parameters go to REST server as HTTP GET parameters
 5 $stock='MSFT';
 6 
 7 $xml = simplexml_load_file("http://localhost/demo/restserver.php?stock=$stock");
 8 
 9 echo "$stock stock price today is ";
10 echo $xml->stockprice;
11 
12 ?>
13 
14 

Basically you don't need to know anything about Web Services or even XML to make and consume REST Web Services.   This assertion greatly irritates a lot of people.

I'm not saying there isn't a need for SOAP and WS-*, just that often simple tools will do the job.  It's just another version of the 80% rule.  This seems to be a theme in my personal consumption of technology.


posted on 2008-10-07 21:16 Blog of JoJo 阅读(1329) 评论(0)  编辑  收藏 所属分类: Linux 技术相关

只有注册用户登录后才能发表评论。


网站导航:
 

<2024年12月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

常用链接

留言簿(6)

随笔档案

文章分类

文章档案

新闻分类

新闻档案

相册

收藏夹

搜索

  •  

最新评论

阅读排行榜

评论排行榜