XML Programming with PHP and Ajax - Netscape

25 downloads 8260 Views 194KB Size Report
Oct 10, 2006 ... XML Programming with PHP and Ajax. By Hardeep Singh. Your knowledge of popular programming languages and techniques is all you need ...
XML Programming with PHP and Ajax

http://www.db2mag.com/shared/printableArticle.jhtml?articleID=...

http://www.db2mag.com/story/showArticle.jhtml;jsessionid=BGWVBCCENYVW2QSNDLPSKH0CJUNN2JVN?articleID=191600027

XML Programming with PHP and Ajax By Hardeep Singh

Your knowledge of popular programming languages and techniques is all you need to put DB2 9's XML capabilities to work in service-oriented architectures and other business scenarios. Programmers frequently use XML to exchange structured and semistructured data between applications as part of a service-oriented architecture (SOA). XML and its related technologies — Document Object Model (DOM), XPath, HTTP, XQuery, and Extensible Stylesheet Language Transformations (XSLT) — provide a powerful environment for rapid application development. Applications built on these technologies can enjoy a smaller footprint, lower maintenance costs, and improved quality and flexibility. DB2 and other relational databases have matured considerably in their XML offerings, making them an ideal choice to store and manage XML data in addition to relational data. DB2 9 XML support (called pureXML) provides the capability to store XML in its pure form (in other words, in annotated, tree-like, hierarchical storage). Inside DB2 9, XML data can be indexed using XML patterns, composed from relational data, decomposed to relational data, and queried, transformed, and published stand-alone or combined with relational data using a mix of SQL/XML and XQuery. Web browsers are also providing more functionality to client script to efficiently handle XML. Using Asynchronous JavaScript and XML (Ajax), Web pages can now make direct remote procedure calls to application servers and use DOM APIs on any returned XML data. I'll show you how to exploit the capabilities provided by DB2 XML, Ajax, and PHP Hypertext Preprocessor (PHP) to write simple XML-based applications. With the help of a sample scenario, you will learn how to make JavaScript calls to a PHP application; how to modify any XML data using DOM and SimpleXML APIs, how to transfer the XML from the client to application to database, and how to create a PHP Web service to publish reports on the XML data using SQL/XML and XQuery.

XML Benefits FIGURE 1. An object wrapper-based application.

Most applications are written to create, store, manipulate, and present business data. Object wrapping is put around the business data to make handling it easier for the business logic. Much of the functionality of these wrapper objects is to give a structure to the business data, based on relationships and formatting rules, and to enable the business logic to manipulate, publish, and serialize the encapsulated data. Figure 1 illustrates a sample life insurance application using object wrappers. Each of the boxes represents an object, and each object has, at a minimum: A constructor Getter and Setter methods Some validation code Serialization of internal object hierarchies. These objects have nothing to do with the actual business logic. The object wrapping is created in order to make it easier for the business logic to manage the business data. The code needed to wrap the data is much larger than the code needed for the business logic. More code introduces more bugs, more rigidity, more maintenance, and more cost. FIGURE 2. An XML-based application.

1 of 6

10/10/06 4:45 PM

XML Programming with PHP and Ajax

http://www.db2mag.com/shared/printableArticle.jhtml?articleID=...

If data variables defined inside an object can be formatted as XML structures and if the main purpose of the object is to manipulate and expose these data structures to the business logic, then a DOM can replace the object. Figure 2 shows the sample insurance application using XML and a DOM wrapper. All the data wrapper objects from Figure 1 are replaced with a single DOM object. The business data is modeled in XML, and the DOM provides the necessary APIs to: Create new XML objects Update the values of XML objects Navigate XML objects Search across the object hierarchy using XPath Serialize and deserialize the XML object hierarchy (in other words, built-in persistence). Using XML eliminates most of the wrapper objects that were needed to manage the business data. The application becomes leaner and focused on the business logic rather than data management.

XML and Architecture Introducing XML into the architecture brings a standardized way to represent the business data. XML gives structure to the data; XML schemas enforce the structure and the formatting rules; DOM APIs and languages such as XQuery, XPath, and XSLT enable business logic to efficiently manipulate, publish, and serialize the data. Because the XML representation of the business data is the same in the client, the middle tier, and the database, the code for manipulating this data is also similar. I'll show you how to build an XML-based application in a three-tier environment, which is made up of: Web client: Asynchronous JavaScript and XML (Ajax), DOM Application server: PHP with SimpleXML Database: DB2 9 with SQL/XML, XQuery.

Scenario Based on ACORD Life & Annuity Data Model Let's consider a simple life insurance scenario in which an XML document representing a new policy is created, queried, manipulated, and moved from one tier to the other. The document is based on the Association for Cooperative Operations Research & Development (ACORD) XML for Life & Annuity specification, which defines the data that the health insurance and annuity industries need to communicate. To request a new policy, a customer provides some basic information. Part of the request is filled in a PHP application and part of it is filled in the client browser. The policy is then stored in a DB2 XML column. In DB2 9, a column of type XML internally stores the XML data as a parsed XML tree separate from the relational data storage. This approach is unique to DB2 9; earlier DB2 versions used the relational storage infrastructure to store XML. This is the flow of the policy XML document between the client and the application: In the Web client, the customer updates the page and clicks Submit. The Web client makes an XMLHTTP request to the PHP application for new blank policy document. The PHP application opens a blank policy document, updates it with a globally unique identifier (GUID), and then returns the document back to the Web client. The Web client traps the returned event using Ajax and retrieves the XML DOM, then fills the document with information entered on the Web page. The Web client uses XMLHTTP to send the updated XML to the PHP application. FIGURE 3. A Web site for creating a new policy request.

2 of 6

10/10/06 4:45 PM

XML Programming with PHP and Ajax

http://www.db2mag.com/shared/printableArticle.jhtml?articleID=...

Figure 3 shows the Web page for creating a new policy request. After the user clicks on the Submit button, the JavaScript function submitPolicy() is called (see Listing 1). This function makes an HTTP request to the PHP application, createNewPolicy.php , to get a blank policy. It also sets up a callback function, fillPolicy() , to trap the events from the HTTP request.

When the first request reaches the PHP application server at the middle tier, a new XML policy document is loaded into the SimpleXML object. Using the SimpleXML API, the TransRefGUID element is updated with a GUID created in the PHP application. header('Content-type: text/xml'); $fileContents = file_get_contents("$basedir/acord.xml"); $dom = simplexml_load_string($fileContents); $dom->TXLifeRequest->TransRefGUID=$guid; echo $dom->asXML();

The document is then sent to the client. For this article we will assume that a GUID was created by some mechanism (for example, a combination of time and a random number). The more important thing is to understand how the XML document representing a policy is treated as an in-memory hierarchy of business objects and how the SimpleXML API (or DOM/XPath) is used to navigate and update this object.

Filling in Basic Customer Information In the Web client, the returned value is read in the fillPolicy() function. The DOM object containing the in-memory representation of the returned XML can now be used to manipulate the policy document. The information entered by the customer on the Web page is used to update the DOM directly. Once the policy is updated with the customer information, the modified DOM object is submitted back to the PHP application using XMLHTTP (see Listing 2). Even the HTML component values are read using a DHTMLDocument Object Model (DOM).

Storing the Policy in DB2 The PHP application stores the incoming XML document directly into the database without needing to parse it (see Listing 3). DB2's pureXML support implicitly parses and stores the incoming XML in a hierarchical DOM-like structure. This XML can now be queried using XML navigation techniques such as XPath (also used in DOM) inside an XQuery statement. DB2 9 also provides the capability to index

3 of 6

10/10/06 4:45 PM

XML Programming with PHP and Ajax

http://www.db2mag.com/shared/printableArticle.jhtml?articleID=...

on any node in the hierarchy.

Exposing Services on the XML Documents Once a new policy is stored in DB2 9, an insurance agent can query it to make a decision about whether to accept the policy or not. The queries for getting reports on new policies are exposed to the client application via Web services. The Web service in this example is written in PHP, which provides a thin interface around calls to DB2 stored procedures that implement the business and transformation logic for the service. Each DB2 stored procedure consists of a single SQL/XML query that filters and transforms the XML policy documents stored in the database to create an output XML document. The PHP Web service then returns the XML document to the client. Let's analyze each stored procedure to see the queries that effectively constitute the Web service implementation.

DB2 query to list all the policies for new customers. The stored procedure that contains the query is called listAllNewCustomers (see Listing 4). The query searches all policy documents in the INFO column of the ACORD table. Inside each XML document, DB2 further drills down to return only those documents in which the code value for the PolicyStatus/@tc attribute is set to 12 (in other words, proposed). The query output is an XML document with a root node newpolicylist that contains a list of TXLife child nodes for each new policy (see Figure 4). FIGURE 4. A SQL/XML query that returns a list of new policies.

Note how the query first navigates the relational schema to get to the XML column DB2ADMIN.ACORD.INFO using the DB2 XQuery function db2-fn:xmlcolumn . Once it reaches the XML column, it further navigates to the appropriate nodes inside the XML Schema using XPath (similar to navigating the DOM using PHP, JavaScript, or any other language). DB2 query to list proposed policies for at-risk customers. This query lists only new customers who are at risk (that is, they answered yes to one of the medical questions). The query is contained in a stored procedure called listAtRiskNewCustomers (see Listing 5). Note: The WHERE clause checks both answer and policy status.

4 of 6

10/10/06 4:45 PM

XML Programming with PHP and Ajax

http://www.db2mag.com/shared/printableArticle.jhtml?articleID=...

DB2 query to evaluate risk for an at-risk new customer. For each policy in the above list, you can list only the questions that elicited yes answers in the health risk section of the policy. The policytype is also returned to show how much the policy is worth in order to evaluate the risk. The stored procedure containing the query (see Listing 6) is called getRiskQuestions(guid) . Note: You will need a version of the DB2 driver that has support for the XML type. Otherwise, you will need to serialize the XML value from the XMLQuery, in each stored procedure, using XMLSerialize. See the developerWorks article "Use DB2 Native XML with PHP" for more detail.

Creating the Web Service The PHP code for the getnewpolicyinfo Web service is a thin wrapper that checks the type of policy report required and makes a call to the appropriate stored procedure. The return value from the call is then sent back to the client (see Listing 7). Note how simple it is to create a web service in PHP. The last three lines expose the function as a Web service. The Web service can be invoked from any client including another PHP application, as Listing 8 shows.

Closing the Loop XML support in all application tiers has matured in the past few years, resulting in a powerful development environment that can change the way business applications are designed. XML provides developers with the ability to define rules and structures for business documents as well as to instantiate the documents in memory as hierarchical objects that can be navigated, modified, and serialized in any of the tiers using standard APIs. Ajax enables Web-based client scripts to call DOM APIs and make remote procedure calls to a middle tier. PHP provides one of the simplest approaches for handling XML and Web services, making it a perfect fit for XML-based application development. The last link in the XML evolution was the database layer. DB2 9 makes that tier capable of XML manipulations. The circle is complete.

The author thanks Cindy Saracco, IBM, for her help.

5 of 6

10/10/06 4:45 PM

XML Programming with PHP and Ajax

http://www.db2mag.com/shared/printableArticle.jhtml?articleID=...

Hardeep Singh is a member of the DB2 XML development team and the architect for DB2 XML tooling. He has more than 22 years of industry experience.

Resources

DB2 9 XML support "Firing up the Hybrid Engine", Anjul Bhambhri, DB2 Magazine, Quarter 3, 2005 "Query DB2 XML Data with SQL," C. M. Saracco, IBM developerWorks, March 2006 "Query DB2 XML Data with XQuery," Don Chamberlin and C. M. Saracco, IBM developerWorks, April 2006 "Develop Java applications for DB2 XML Data," C. M. Saracco, IBM developerWorks, May 2006 "XML application migration from DB2 8.x to DB2 Viper, Part 1: Partial updates to XML documents in DB2 Viper," Hardeep Singh, IBM developerWorks, May 2006 Return to Article

6 of 6

10/10/06 4:45 PM