create a php webservice in 5min, using php, soap and wsdl technology , nusoap

Upload: aureliano-duarte

Post on 14-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 Create a PHP Webservice in 5min, Using PHP, SOAP and WSDL Technology , NuSOAP

    1/5

    Create a PHP webservice in 5min, Using PHP, SOAP

    and WSDL Technology , NuSOAP

    Posted: November 25, 2009 inTechnology

    22

    IntroductionUnless you have been living in a cave somewhere without Internet access for the lastfew years, you have undoubtedly heard of XML, SOAP and Multi-Tiered ApplicationProgramming. If you are like many programmers, including myself, you were quitetaken aback by these ideas and technologies. You may have gone so far as to simplydismiss them as irrelevant to your skill set. Its time to wake up and realize theyrehereto stay and for good reason!.

    XML and SOAP, and in turn Multi-Tiered Programming, are technologies that can take

    you from being a run of the mill code hacker to a professional application developer thatactually builds cool things that work and which other people can work on. Thesetechnologies enable you to build applications that separate data from presentation, keepthings organized and enable your application to scale as your needs and user baseincreases.

    If you believe like I do that the Internet is the ultimate building ground of ourfuture,then you have to see that the hackish method in which most applications for theweb are built and designed is pitiful. I know that I am quite guilty of it, myself. Manytimes I get an itch and I just scratch it without thinking of what the future holds or themaintainability of my application. Sure the job gets done; the itch has gone away

    momentarily. But when the itch comes back six months down the road and I have to addor modify features, I am utterly disappointed in myself over the sorry shape of my code.You may be asking, how can XML and SOAP help me to avoid poor applicationdesign? Well, by themselves they wont help at all. First and foremost you must getyourself into the mind set that it needs to take place. XML and SOAP are just two toolsthat will allow you to accomplish your goal.

    Today we will build a Web Service using SOAP. In doing so, I hope that you willbecome familiar with the technology so that you can start incorporating it into yourfuture applications.

    DefinitionsBefore we get too much further along, lets make sure we are all on the same footingregarding the basic terminology that we will deal with in this tutorial.

    *XML: XML is the Extensible Markup Language. It is designed to improve thefunctionality of the Web by providing more flexible and adaptable informationidentification. (http://www.ucc.ie/xml/#acro) http://www.ucc.ie/xml/#acro) In otherwords, XML is a method for describing your data. For the purpose of this tutorial, wewill not be directly manipulating any

    XML. Instead, we will examine the XML resulting from our scripts. The libraries andprotocols we will use through this tutorial will handle the XML manipulation for us.

    http://greatgandhi.wordpress.com/category/technology/http://greatgandhi.wordpress.com/category/technology/http://greatgandhi.wordpress.com/category/technology/http://greatgandhi.wordpress.com/2009/11/25/create-a-php-webservice-in-5min-using-php-soap-and-wsdl-technology-nusoap/#commentshttp://greatgandhi.wordpress.com/2009/11/25/create-a-php-webservice-in-5min-using-php-soap-and-wsdl-technology-nusoap/#commentshttp://www.ucc.ie/xml/#acrohttp://www.ucc.ie/xml/#acrohttp://www.ucc.ie/xml/#acrohttp://www.ucc.ie/xml/#acrohttp://www.ucc.ie/xml/#acrohttp://www.ucc.ie/xml/#acrohttp://www.ucc.ie/xml/#acrohttp://greatgandhi.wordpress.com/2009/11/25/create-a-php-webservice-in-5min-using-php-soap-and-wsdl-technology-nusoap/#commentshttp://greatgandhi.wordpress.com/category/technology/
  • 7/30/2019 Create a PHP Webservice in 5min, Using PHP, SOAP and WSDL Technology , NuSOAP

    2/5

    *SOAP: Simple Object Access Protocol. SOAP is a lightweight protocol for exchangeof information in a decentralized, distributed environment. It is an XML based protocolthat consists of three parts: an envelope that defines a framework for describing what isina message and how to process it, a set of encoding rules for expressing instances of

    application-defined datatypes, and a convention for representing remote procedure callsand responses. ((http://www.w3.org/TR/2000/NOTE-SOAP-20000508/)http://www.w3.org/TR/2000/NOTE-SOAP-20000508/)

    SOAP is what you are here for. We will develop both a client and a server for ourSOAP service. In this tutorial, we will be using the NuSOAP library.((http://dietrich.ganx4.com/nusoap/index.php )http://dietrich.ganx4.com/nusoap/index.php)

    *WSDL: WSDL is an XML format fordescribing network services as a set ofendpoints operating on messages containing either document-oriented or procedure-

    oriented information.((http://www.w3.org/TR/wsdl) http://www.w3.org/TR/wsdl) As with XML, we will not

    be directly any WSDL documents. The wonderful NuSOAP library will generateWSDL documents for us. Whatyou need to know about WSDL is that it is a document that describes a Web Service. Itcan tell a client how to interact with the Web Service and what interfaces that WebService provides.

    *Client: We will define a Client as a script that uses a Web Service.*Server: Conversely, a Server will be defined as a script that provides a Web Service.

    Define Our GoalToday we are going to build a Web Service that will return a stock price given a

    particular stock symbol. This is a classic example of where Web Services are of greatuse. You may be building an application that needs the data and could very easily just

    pull the data directly from your data source. Building a Web Service for it, however,allows give other applications easy access the same data in the future. It also separatesthe data extraction from the data source from the application itself. Say you were storingthe data in a MySQL database but later decided to move it to a SQLite database inthis scenario your application wouldnt know the difference. Its calls to the Web Serviceremain unchanged.

    To provide a stock quote service you will have to have the stock prices and symbolsstored in some fashion or another. This tutorial is not going to concentrate on thestorage mechanism or how to obtain the prices. I will simply provide you will a tableschema and some sample data to work with.

    CREATE TABLE `stockprices` (`stock_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,`stock_symbol` CHAR( 3 ) NOT NULL ,`stock_price` DECIMAL(8,2) NOT NULL ,PRIMARY KEY ( `stock_id` ));

    INSERT INTO `stockprices` VALUES (1, ABC, 75.00);INSERT INTO `stockprices` VALUES (2, DEF, 45.00);

    http://www.w3.org/TR/2000/NOTE-SOAP-20000508/http://www.w3.org/TR/2000/NOTE-SOAP-20000508/http://www.w3.org/TR/2000/NOTE-SOAP-20000508/http://www.w3.org/TR/2000/NOTE-SOAP-20000508/http://www.w3.org/TR/2000/NOTE-SOAP-20000508/http://dietrich.ganx4.com/nusoap/index.phphttp://dietrich.ganx4.com/nusoap/index.phphttp://dietrich.ganx4.com/nusoap/index.phphttp://www.w3.org/TR/wsdlhttp://www.w3.org/TR/wsdlhttp://www.w3.org/TR/wsdlhttp://www.w3.org/TR/wsdlhttp://www.w3.org/TR/wsdlhttp://www.w3.org/TR/wsdlhttp://www.w3.org/TR/wsdlhttp://dietrich.ganx4.com/nusoap/index.phphttp://www.w3.org/TR/2000/NOTE-SOAP-20000508/http://www.w3.org/TR/2000/NOTE-SOAP-20000508/
  • 7/30/2019 Create a PHP Webservice in 5min, Using PHP, SOAP and WSDL Technology , NuSOAP

    3/5

    INSERT INTO `stockprices` VALUES (3, GHI, 12.00);INSERT INTO `stockprices` VALUES (4, JKL, 34.00);

    Create a SOAP serverThe first thing we need to do is to create the SOAP server. This is the script that will

    fetch the data from the database and then deliver it to the Client. One wonderful thingabout the NuSOAP library is that this same Server script will also create a WSDLdocument for us.

    The first step is to create a function that will fetch the data we want. Create this functionjust as you would any other. It is just straight up PHP. The one trick is to name thefunction something sensible, as this will be the name that is used when the Clientcontacts the Server.

    Now, it is time to turn this function into a Web Service. Basically, all we have to do isinclude the NuSOAP library, instantiate the soap_server class and then register the

    function with the server. Lets go through it step by step, after which I will present thecompleted script.

    The first thing necessary is to simply include the NuSOAP library.

    require(nusoap.php);

    Next, instantiate an instance of the soap_server class.

    $server = new soap_server();

    create for us. Specifically we specify the name of the server and the namespace, in thatorder.

    $server->configureWSDL(stockserver, urn:stockquote);

    Now, we register the function we created with the SOAP server. We pass severaldifferent parameters to the register method. The first is the name of the function we areregistering.The next parameter specifies the input parameters to the function we are registering.

    Notice that it is an array. The keys of the array represent the names of the input

    parameters, while the value specifies the type of the input parameter. One thing thatpure PHP programmers might find odd is that I had to specify what types my input andreturn parameters are with the designations of xsd:string and xsd:decimal. It is requiredthat you describe your data properly. You are not dealing with a loosely typed languagehere. The third parameter to the register method specifies the return type of theregistered function. As shown below, it is fashioned in the same way as the last

    parameter, as an array. The next two parameters specify the namespace we are operatingin, and the SOAPAction. For more information on the SOAPAction see(http://www.oreillynet.com/pub/wlg/2331) http://www.oreillynet.com/pub/wlg/2331.

    $server->register(getStockQuote,

    array(symbol => xsd:string),array(return => xsd:decimal),

    http://www.oreillynet.com/pub/wlg/2331http://www.oreillynet.com/pub/wlg/2331http://www.oreillynet.com/pub/wlg/2331http://www.oreillynet.com/pub/wlg/2331http://www.oreillynet.com/pub/wlg/2331http://www.oreillynet.com/pub/wlg/2331http://www.oreillynet.com/pub/wlg/2331
  • 7/30/2019 Create a PHP Webservice in 5min, Using PHP, SOAP and WSDL Technology , NuSOAP

    4/5

    urn:stockquote,urn:stockquote#getStockQuote);

    Now, we finally finish it off with two more lines of code. The first simply checks if$HTTP_RAW_POST_DATA is initialized. If it is not, it initializes it with an empty

    string. The next line actually calls the service. The web request is passed to the servicefrom the $HTTP_RAW_POST_DATA variable and all the magic behind the scenestakes place.

    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)? $HTTP_RAW_POST_DATA : ;$server->service($HTTP_RAW_POST_DATA);

    Here is the completed server script which I have saved in a file named stockserver.php.

    configureWSDL(stockserver, urn:stockquote);

    $server->register(getStockQuote, array(symbol => xsd:string),array(return => xsd:decimal),urn:stockquote,urn:stockquote#getStockQuote); $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)? $HTTP_RAW_POST_DATA : ;$server->service($HTTP_RAW_POST_DATA);?>

    The WSDL DocumentAt this point you have a fully functioning SOAP Server. Clients can connect to it andrequest data. If you havent done so already, bring up the script in your browser and seewhat you get. You should get a page giving you a link to the WSDL document for theServer. Click on it and you should see the resulting WSDL document. Surprise,surprise, it is in XML! If you read over this document, you will see that it describeswhat happens for a request and as a response for your particular SOAP Service.

    Note that while it is possible to create a SOAP Server without having it create theWSDL file, I recommend creating the WSDL document anyway. It is simple enough, sowhy not?

    Creating a SOAP ClientCreating a SOAP Client to access our Server with is just as simple as creating theServer was. Understand though that the Client does not necessarily need to be a PHPClient. The SOAP Server we just created can be connected to by any type of Client,whether that be Java, C#, C++, etc.

    To create the SOAP Client, all we need to do are three things. First, include theNuSOAP library. This is done just as it was for the Server.

    require_once(nusoap.php);

  • 7/30/2019 Create a PHP Webservice in 5min, Using PHP, SOAP and WSDL Technology , NuSOAP

    5/5

    Secondly, we need to instantiate the soapclient class. We pass in the URL of the SOAPServer we are dealing with.

    $c = new soapclient(http://localhost/stockserver.php ;);

    Last make a call to the Web Service. The one caveat is that the parameters to the WebService must be encapsulated in an array in which the keys are the names defined forthe service. You will see that I have an array key named symbol because that is thename of the input parameter of my function. If you remember how we specified theinput parameters when we registered the function with the server, you will see that thisis very similar.

    $stockprice = $c->call(getStockQuote, array(symbol => ABC));

    Now, here is the completed Client script, which I have saved in a file named

    stockclient.php.

    call(getStockQuote,array(symbol => ABC));echo The stock price for ABC is $stockprice.;?>

    There it is. It really is that simple.

    ConclusionHopefully after reading through this tutorial you have an understanding of how simple itis to create a SOAP Server and Client with NuSOAP. It simply astonished me howutterly simple it was after I actually took a look at it! Before I ever laid eyes on it I haddreams of a complex system that would take months to utilize. Luckily, NuSOAP camealong and made that task simpler than anyone could ever ask for.

    As you can see, SOAP is a wonderful tool for separating your application into smallermore manageable pieces. Do realize that SOAP isnt the cure all for everything. Itsoveruse is just as bad as any other poor design. The key to a good application design is

    patience and planning. Sit down, take out the old pencil and paper and write thingsdown. Understand what you are really getting yourself into and ask lots of What If

    questions. Think about the future of the application and ask yourself about the differentways it may be used in the future. The number one pitfall of application design ispainting yourself into a corner. If you just thought about it ahead of time you could havestarted at the other side of the room.

    http://localhost/stockserver.phphttp://localhost/stockserver.phphttp://localhost/stockserver.phphttp://localhost/stockserver.php