MySQL /PHP Database Applications Second Edition phần 8 pps

81 321 0
MySQL /PHP Database Applications Second Edition phần 8 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

What’s all that other stuff? Well, the namespace definition states where the func- tion getInseam() can be found on the network. The SOAP-ENV:encodingStyle value further standardizes the way in which simple and complex data types are pre- sented on each side of the SOAP transaction. Next comes the question of whose inseam measurement you want to retrieve. This specifier should be presented to the function as an argument, which is to say that in a traditional (intra-program) call to the function the syntax looks something like this: GetInseam(“Joe Bloggs”) In SOAP you’re obliged to do things a little differently. Remember that you are already inside a getInseam element, which means you have already made clear that getInseam is the function you’re calling. You need to specify the argument now. Logically enough, you do that with an element whose name matches the argu- ment name, as specified in the remote class: <person xsi:type=”xsd:string”>Joe Bloggs</zipcode> With that done, you close out the getInseam element and the Body element, as well: </ns1:getInseam> </SOAP-ENV:Body> How does all this look in practice? The next section takes a look at a request/ response pair in which a call to getInseam() is made and replied to. A typical request/response pair A SOAP transaction consists of a request and a response, similar in lots of ways to the request and response that are made when you order up a Web page with your browser. Remember, SOAP transmissions are nothing more than passages of text, marked up with XML in such a way that they serve special SOAP purposes. THE REQUEST Here’s a complete request: <?xml version=’1.0’ encoding=’UTF-8’?> <SOAP-ENV:Envelope xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”> <SOAP-ENV:Body> <ns1:getInseam 522 Part IV: Not So Simple Applications xmlns:ns1=”urn:referenceToWebService” SOAP- ENV:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/”> <person xsi:type=”xsd:string”>Joe Bloggs</person> </ns1:getInseam> </SOAP-ENV:Body> </SOAP-ENV:Envelope> A request, at its simplest, is just a Body element inside an Envelope element. You can make things more complicated if you want— the specification allows for, among other things, a supplementary Header element that describes the relationship among several SOAP messages or that describes how the message should be routed. THE RESPONSE Responses, in terms of format, bear a close resemblance to requests. They have exactly the same envelope formats, and the body is different only in terms of the name given to the element being sent. Usually, that’s the same as the element name specified in the request, with Response appended. Here’s a complete response to match your earlier request: <?xml version=’1.0’ encoding=’UTF-8’?> <SOAP-ENV:Envelope xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”> <SOAP-ENV:Body> <ns1:getInseamResponse xmlns:ns1=”urn:referenceToWebService” SOAP- ENV:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/”> <return xsi:type=”xsd:float”>34.0</return> </ns1:getInseamResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Not too complicated, right? Joe Bloggs has an inseam measurement of 34. That’s probably 34 inches. However, could Joe be a child with a 34-centimeter inseam? This response gives us no way to tell. To encode complex data structures into SOAP messages (both requests and responses), you have to dig a bit deeper into the specification. The next section takes a look at how to encode an array into a SOAP message. COMPLEX DATA TYPES Complex data types are multipart data types. An array is an example of a complex data type in which the members are accessed by number. A struct, as those of you Chapter 16: SOAP 523 who code in C know, is an “associative array,” in which the array elements are accessed by name rather than by number. In the case of the inseam-returning Web service, it would be handy to know what unit applies to the floating-point number that comes back in response to a request. You can modify the contents of the Body element to hold this information in a struct. The struct defined here contains two elements: the value (the floating-point value) and the unit (the string inches, centimeters, or whatever). <return xmlns:ns1=”urn:referenceToWebService” xsi:type=”ns1:inseamInfo”> <unit xsi:type=”xsd:string”>inch</unit> <value xsi:type=”xsd:double”>34.0</value> </return> In this mode of using SOAP, the Web service referred to defines a struct called inseamInfo, which is comprised of a string called unit and a float called value. By stating in the opening return tag that the return value is of type inseamInfo, you make it legal to refer to these sub-elements. There’s a lot more to do with the SOAP specification, and not all of it obscure. Some of the more interesting and useful bits have to do with how errors and other exceptional conditions are noted via SOAP, while others have to do with how to describe other compound data types in SOAP messages. Such aspects of the specifi- cation are beyond the scope of this chapter, but are certainly worth studying. There’s lots of information on SOAP at the World Wide Web Consortium site, including an overview (http://www.w3schools.com/soap/ soap_intro.asp ) and a tutorial (http://www.w3schools.com/soap/ default.asp). Code Overview Key to any successful career in software design is the ability to freely make use of the work of other people. The open-source movement is all about this practice, and, thankfully, a considerable amount of software is available for the taking. NuSphere Corporation — makers of PHPEd, a PHP development environment — have developed a set of classes called SOAPx4, which has since been modified and renamed NuSOAP. It’s a remarkably capable SOAP suite, doing pretty much all the heavy lift- ing for you. If you’re using a PHP development environment (such as NuSphere’s PHPEd version 3 or later) you’ll probably find it even easier to work with NuSOAP. You can add your own modules — such as new releases of PHP — to your environ- ment after you set it up initially. 524 Part IV: Not So Simple Applications The best place to begin the process of getting NuSOAP is on the Web site of Dietrich Ayala (http://dietrich.ganx4.com/nusoap/). His site includes links to the latest version of NuSOAP, as well as links to documenta- tion, mailing lists, and other resources for developers and architects. The essence of NuSOAP NuSOAP is a series of classes. You copy the downloaded files (most of them .php files) to your include directory and then make reference to them in your own PHP classes. The NuSOAP classes take care of such work as creating SOAP client and server objects and managing the transmission of SOAP messages among those objects. The NuSOAP classes even take care of something we discussed earlier in this chapter: the encoding of values into properly structured XML. For the most part, you can think of the NuSOAP classes as black boxes. You just stick the PHP files in your include directory and then cease worrying about them. All you have to do is be aware, as you’re writing PHP programs that you want to act as Web-service providers or consumers, that you have some new classes avail- able to you. Suppose you want to build a server. In other words, you want to make a PHP function available as a Web service. Once you’ve added the required include state- ment (as follows) you have a four-step process ahead of you. require_once(‘nusoap.php’); 1. Create a server object. All you need to do is set a variable equal to a soap_server object (soap_server being one of the classes made avail- able by your inclusion of NuSOAP). It’s easy: $server = new soap_server; 2. Register one of your local functions with that new soap_server object. Again, no problem. You simply invoke the register() function of the soap_server object, specifying one of your local functions as the sole argument. The complete syntax looks like this: $server->register(‘getInseam’); 3. Define a function called getInseam(). This can contain whatever code you want. Presumably, in this case, it accesses a database to retrieve a named party’s inseam measurement and then returns a value and unit. The skeleton of the function looks something like this: function getInseam($name) { // Function code } Chapter 16: SOAP 525 4. Tune the soap_server object in to the HTTP requests it’s meant to moni- tor and enable it to respond to them. You do this with a standard piece of code that rarely varies across NuSOAP applications: $server->service($HTTP_RAW_POST_DATA); Those are the key elements of a SOAP server as implemented under NuSOAP. What, then, about the client that speaks to this service? It’s even simpler. NuSOAP clients have to include the nusoap.php file as well. Once that’s done, they need only to instantiate a soapclient object (the soapclient object, again, being part of the NuSOAP collection) with the URL of the service to be called as an argument. If you had a service called getInseam() on http://www.wiley.com (there isn’t one, by the way), you could do this to create a SOAP client to call it: $soapclient = new soapclient(‘http://www.wiley.com/getInseam.php’); Then you could send a call to the server via that client, like this: write( $soapclient->call(‘getInseam’,array(‘name’=>’Joe Bloggs’))); Pretty cool, eh? The arguments are sent as an array that enables you to match sent values to expected values as you like. A simple NuSOAP service call Now we take a quick look at a “Hello, user” program as written with the help of the NuSOAP classes. Really you see two programs here: a client and a server. The server exposes a simple routine that takes in a string (the user’s name) and returns a string made up of the word Hello and the provided name followed by a period. In other words, if you send the service Ralph as an argument, the service says, Hello, Ralph. First you need a server. The server has the same name as the service you want to expose, so in this case name it hello.php. Its full contents are as follows: require_once(‘nusoap.php’); $server = new soap_server; $server->register(‘hello’); function hello ($name){ return “Hello $name.”; } $server->service($HTTP_RAW_POST_DATA); 526 Part IV: Not So Simple Applications Not complicated, really. It’s just a matter of registering an otherwise ordinary function with a special server object and then setting that server to deal with HTTP activity. Every server needs a client. The client file, in this case, can be called anything and can reside anywhere the server can be accessed via HTTP. require_once(‘nusoap.php’); $soapclient = new soapclient(‘http://yourdomain.com/hello.php’); write($soapclient->call(‘hello’,array(‘name’=>’Ralph’))); Pretty simple, really. You just bind your client to the service (this example assumes you know exactly where it is and what it’s called) and call that client as you need values from it. The glory of NuSOAP is its simplicity. There’s more to it than we’ve just dis- cussed — you will see some more complexity as the chapter continues — but there’s no doubt that NuSOAP makes it unbelievably easy to incorporate SOAP client and server capability into PHP programs. It can be said that, other than for educational reasons, there’s never a reason to write your own SOAP client and server classes anymore. You’d be reinventing an already highly refined wheel. Determining the Goals of the Application It’s time to have a look at SOAP messaging under PHP, and at some of the ways you can communicate with publicly accessible Web services via SOAP. The rest of this chapter focuses on an application that requests information from different sources, parses it, and presents it to the user. Our goal is to use the Web services made available by a couple of providers — the Barnes & Noble bookstore and the Babelfish translation service — to gather infor- mation. Specifically, we use the Barnes & Noble service to gather information about books that interest us, and the Babelfish service to translate a passage of text from English into a series of European languages. The Barnes & Noble application takes an International Standard Book Number (ISBN) and returns the price of the book identified by that number at Barnes & Noble’s Web site, www.bn.com. If you send it the value 0440234816, which is the ISBN of Karen Marie Moning’s novel To Tame a Highland Warrior, you can expect to see the following output from your local PHP program: The price of book number 0440234816 is $6.99. That price really is a bargain for “a medieval romance with paranormal overtones.” Chapter 16: SOAP 527 The Babelfish application (http://babelfish.altavista.com) enables you to translate a phrase from English to French, German, Italian, Spanish, or Portuguese. By default, the program is set up to send the value From beneath you, it devours to Babelfish. The application gives you the following translations, which are vari- ously accurate. Generally, if you see the English word in the translation, it means Babelfish was stumped. ◆ French — De sous vous, il devours. ◆ German — Von unter Ihnen es devours. ◆ Italian — Sotto da voi, esso devours. ◆ Spanish — Debajo de usted, él devours. ◆ Portuguese — Abaixo de você, ele devours. Clearly, Babelfish has problems with devours. The interesting aspect of this is that everything is done with Web services. You send parameters (the ISBN in the former example, and the target language and original phrase in the latter), and the Web services (which aren’t hosted locally, per- haps obviously) return the strings you need. How does it work? The answer to this question requires a deeper exploration of our application’s code, which follows in the next section. Code Breakdown To see what’s going on in the two applications, you have to take a close look at the PHP code itself. Both the Babelfish application and the Barnes & Noble application are clients — they exist for the purpose of talking to servers that are implemented somewhere else. In this case, both of them speak to servers on XMethods (www.xmethods.com or www.xmethods.net), a site that hosts a number of Web services for the purposes of testing and experimentation. You don’t need to know how those remote services are implemented. They could be in Java, C, or PHP. It really makes no difference to you, because they’re set up to work with SOAP requests from over the Internet. The Barnes & Noble application The Barnes & Noble client sends an ISBN value (which uniquely identifies a book in print) to a Web service, which returns the selling price of the corresponding book on the Barnes & Noble Web site, www.bn.com. It prints out a simple string, indicat- ing either the price of the book, the fact that www.bn.com doesn’t list the book, or the fact that there was an error in the execution of the Web service. 528 Part IV: Not So Simple Applications THE HEADER FILE Many of the files in the Barnes & Noble and Babelfish applications call a header file initially. The header file, header.php, does two important things. First, it imports the critical nusoap.php file. It also specifies how the local applications deal with errors. Here is header.php: <?php require_once(preg_replace(‘/soap.*/’,’book.php’,realpath(__FILE__))) ; function soap_errors() { $oh = set_error_handler(‘error_handler’); if (empty($oh)) { set_handler(0, H_ERROR); set_handler(E_ALL, H_LOG); } else { restore_error_handler(); } } soap_errors(); // include the class and function definitions for this application require_once(‘lib/nusoap.php’); ?> THE CLIENT FILE The client file actually handles the process of instantiating a SOAP client that con- nects to a publicly accessible Web service providing Barnes & Noble prices (really, it just tells NuSOAP to do the dirty work). Here it is: <?php // include the SOAP classes require_once(dirname(__FILE__).’/header.php’); // define parameter array (ISBN number) $param = array(‘isbn’=>’0385503954’); // define path to server application $serverpath =’http://services.xmethods.net:80/soap/servlet/rpcrouter’; //define method namespace $namespace=”urn:xmethods-BNPriceCheck”; Chapter 16: SOAP 529 // create client object $client = new soapclient($serverpath); // make the call $price = $client->call(‘getPrice’,$param,$namespace); // if a fault occurred, output error info if (isset($fault)) { print “Error: “. $fault; } else if ($price == -1) { print “The book is not in the database.”; } else { // otherwise output the result print “The price of book number “. $param[‘isbn’] .” is $”. $price; } // kill object unset($client); ?> So, what’s going on here? Some of it should look familiar. First of all, the pro- gram defines an array: $param = array(‘isbn’=>’0385503954’); Then, it sets a variable ($serverpath) that contains, as a string, a URL: $serverpath =’http://services.xmethods.net:80/soap/servlet/rpcrouter’; What’s that URL? Well, if you call it up in an ordinary browser, you get an error. The error says, in effect, that you can’t use a browser in this situation because this isn’t a document at all — it’s a remote procedure call (RPC) router. As such, you have to send it text (that is, SOAP XML) via the HTTP POST command. This makes sense, because you want to send something from your client to the remote Web service. Then you specify, on that remote site, the namespace you’re working with. This line of code serves that purpose: $namespace=”urn:xmethods-BNPriceCheck”; The purpose of the reference to that site is to examine the Web Services Description Language (WSDL) file that exists there. WSDL describes the Web services that exist at a particular site, and the particular methods they expose. You know that BNPriceCheck is a meaningful namespace on XMethods because you saw it adver- tised at http://services.xmethods.net. (It’s also described programmatically at http://www.xs.net/sd/2001/BNQuoteService.wsdl.) 530 Part IV: Not So Simple Applications The next line should look familiar. It’s the instantiation of a NuSOAP soapclient object that’s bound to the XMethods RPC router: $client = new soapclient($serverpath); With all that done, you can make a call to the remote service, expecting a single value in return: $price = $client->call(‘getPrice’,$param,$namespace); That line invokes the call() function of the local soapclient object (as con- tained in the $client handle). It sends along three arguments: ◆ getPrice — The name of the function you are calling ◆ $param — The struct you established earlier, containing the ISBN value ◆ $namespace — The namespace you got from the WSDL file, making it clear to the RPC router that you want to send your query to the Barnes & Noble service After the request goes off — and remember, it’s the job of NuSOAP to manage the mechanics of sending the request over HTTP (using POST) and dealing with the response when it comes — you have only to react to the string that you get back. It’ll be one of three things: An indication that the service experienced an error, an indication that the ISBN you sent doesn’t correspond to a book in the database, or a price value. Here’s the code that figures out which: if (isset($fault)) { print “Error: “. $fault; } else if ($price == -1) { print “The book is not in the database.”; } else { print “The price of book number “. $param[isbn] .” is $”. $price; From that code you see that you’re expecting a floating-point value if the book is in the database, or -1 if it’s not. If a variable called $fault (defined in NuSOAP) exists, it means there was a problem in the service’s execution and an error field in the Header element of the SOAP response was used (have a look at the SOAP spec- ification for information on how Header elements indicate error conditions). Chapter 16: SOAP 531 [...]... What’s on the CD-ROM APPENDIX B HTML Forms APPENDIX C Brief Guide to MySQL/ PHP Installation and Configuration APPENDIX D MySQL Utilities APPENDIX E MySQL User Administration APPENDIX F PHP Function Reference APPENDIX G Regular Expressions Overview APPENDIX H Helpful User-Defined Functions APPENDIX I PHP and MySQL Resources APPENDIX J MySQL Function Reference Appendix A What’s on the CD-ROM THIS APPENDIX... Chapter 17: Project Management Figure 17-2: Edit Project page Figure 17-3: Calendar view 539 540 Part IV: Not So Simple Applications Figure 17-4: Add New Task page Figure 17-5: Project Admin home page Chapter 17: Project Management Designing the Database Key to this application is its database Much of the work that the project-management application does is essentially note keeping about which files fit... projects, where they are, who owns them, and what their status relative to established deadlines is This information is the sort that databases like to contain for us The entirety of the project management information store is contained in a database called projects The projects database contains a number of tables, each of which tracks various aspects of the project management mission Figure 17-6 shows the... projects database User types The values that can be assigned to users to dictate their privileges are contained in the user_types table The table contains an incremented integer field called user_type_id that serves as the primary key, and a user_type field that contains English words that describe the type of user 541 542 Part IV: Not So Simple Applications The SQL scripts that create the database. .. the user’s local file system and encoding it into the database Upload duties are the domain of savefile.php, which capitalizes upon PHP’s ability to work with a traditional computer file system and also its ability to interact with the contents of a relational database The code first sets out to determine whether the file already exists in the database If it does not, the application proceeds to create... the application across many transactions This makes session management a necessity We use PHP’s library of session-management functions and objects, just as we did in other applications in this book 537 5 38 Part IV: Not So Simple Applications ◆ Once users have logged in, they should be able to view the status of the projects they’re involved in They’ll want to see which files they are responsible for... Aside from the database, the core of the project management application’s functionality is in a series of PHP pages that closely parallel the application’s essential functions (refer back to the requirements described earlier in this chapter in the “Necessary pages” section) The program also makes use of a series of classes that serve as software representations of logical entities, such as database connections... Project Management to its deadline The user can see what tasks are associated with each project, and can establish a new project record in the database Creating a new project If the user chooses to create a new project, he or she is prompted for all the details the database requires in its project record The user gets an HTML form that asks for the project’s title and description, its due date, its present... file the user uploads — which the user does via a file upload interface of the sort that’s standard to his or her operating system — in the files table of the database Viewing a file When a version of a project file exists in the files table of the database, the application displays it to the user The application lists the PHP code directly into the user’s browser, where he or she can examine or save it... md5($this->password)); if ($this->user_type()) { $query = ‘ and ut.user_type = ? ‘; $bind[] = $this->user_type(); } $row = $this->dbh()>getRow($query,$bind,DB_FETCHMODE_ASSOC); if (count($row) > 0) 547 5 48 Part IV: Not So Simple Applications { $this->build($row); return TRUE; } return FALSE; } There’s some code to deal with encryption in there (the password is passed as a hash), but essentially that function determines . in the execution of the Web service. 5 28 Part IV: Not So Simple Applications THE HEADER FILE Many of the files in the Barnes & Noble and Babelfish applications call a header file initially page Figure 17-5: Project Admin home page 540 Part IV: Not So Simple Applications Designing the Database Key to this application is its database. Much of the work that the project-management application. array (ISBN number) $param = array(‘isbn’=>’0 385 503954’); // define path to server application $serverpath =’http://services.xmethods.net :80 /soap/servlet/rpcrouter’; //define method namespace $namespace=”urn:xmethods-BNPriceCheck”; Chapter

Ngày đăng: 12/08/2014, 21:20

Từ khóa liên quan

Mục lục

  • Part IV Not So Simple Applications

    • 16 SOAP

      • Overview of SOAP

        • A typical request/ response pair

        • Code Overview

          • The essence of NuSOAP

          • A simple NuSOAP service call

          • Determining the Goals of the Application

          • Code Breakdown

            • The Barnes & Noble application

            • The Babelfish application

            • Writing a SOAP server application

            • Summary

            • 17 Project Management

              • Determining the Goals of the Application

                • Necessary pages

                • Designing the Database

                  • User types

                  • Application users

                  • Project and task status

                  • Projects

                  • Project- user mappings

                  • Tasks

                  • Files

                  • Code Overview

                    • Logging in and establishing a session

                    • Showing active projects

                    • Creating a new project

                    • Uploading a file

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan