ptg 342 Chapter 13 PHP in WebSphere sMash Table 13.16 Database Results Functions Function Description dataClobLength data_clob_length Returns the length of the Clob resource data. Arguments: Clob handle—The source Clob to process. Returns: The length of the Clob as a double. dataBlobGetBytes data_blob_get_bytes Returns the contents of the Blob resource as a string. Arguments: Blob handle—The source Blob. int position—Starting byte position to access. Int length—Number of bytes to process. Returns: String containing returned value. dataBlobLength data_blob_length Returns the length of the Blob resource data. Arguments: Blob handle—The source Blob to process. Returns: The length of the Blob as a double. dataIteratorHasNext data_iter_has_next Returns true if there is a next item on the Result. Arguments: Iterator handle—Iterator to test for more values. Returns: True if there are more values; false otherwise. dataIteratorNext data_iter_next Returns the next item, and removes it from the Iterator. Arguments: Iterator handle—Iterator to retrieve values from. Returns: Next item in Iterator. dataIteratorRemove data_iter_remove Removes the next item from the Iterator. Arguments: Iterator handle—Iterator containing values. Download from www.wowebook.com ptg WebSphere sMash PHP Extensions 343 Table 13.16 Database Results Functions Function Description dataNewResultHandler data_new_result_handler Creates an instance of ResultHandler for use with the data- Query API. Provides for custom handling of result sets. Arguments: String name—Fully qualified class name of a ResultHandler instance. Returns: Resource that can be passed into dataQuery calls. dataResultSetAbsolute data_rs_absolute Sets the current row index relative to either the beginning or the end of the ResultSet. Arguments: ResultSet rs—ResultSet to alter. int row—Row reference to set pointer location. Positive number references form beginning of RS, negative walks backwards from end of RS. Returns: boolean—True if pointer adjustment worked; false otherwise. dataResultSetClose data_rs_close Closes the ResultSet resource. Arguments: ResultSet rs—resultSet handle to release. Returns: boolean—True if close worked; false otherwise. dataResultSetGetColumnCount data_rs_get_column_count Returns the number of columns in the ResultSet resource. Arguments: ResultSet rs—ResultSet to process. Returns: Number of columns in ResultSet, or -1 on error dataResultSetGetColumnName data_rs_get_column_name Returns the name of the given column in the ResultSet. Arguments: ResultSet rs—ResultSet to process. int index—Column index to process. Returns: String containing name of the column, based on table col- umn name or field alias from query, or NULL on error. Download from www.wowebook.com ptg 344 Chapter 13 PHP in WebSphere sMash Table 13.16 Database Results Functions Function Description dataResultSetGetObject data_rs_get_object Returns the value of the given column. Arguments: ResultSet rs—ResultSet to process int or String column—Column to process. May be index based (starting at 1), or accessed by name. Returns: Column value as an object with no data type coercion implied. dataResultSetGetRow data_rs_get_row Returns the index of the current row. The index of the first row is 1. Arguments: ResultSet rs—ResultSet to process. Returns: int—index of current row pointer within the ResultSet, or -1 on error. dataResultSetNext data_rs_next Move the internal position of the ResultSet resource to the next row. Arguments: ResultSet rs—ResultSet to process. Returns: boolean—True if next row, or false at end of ResultSet list. dataResultSetPrevious data_rs_previous Move the internal position of the ResultSet resource to the pre- vious row. Arguments: ResultSet rs—ResultSet to process. Returns: boolean—True if previous row, or false at beginning of ResultSet list. Download from www.wowebook.com ptg WebSphere sMash PHP Extensions 345 Database Transaction Functions Database transactions are used to perform multiple data manipulations statements as a single unit of work. Table 13.17 lists the functions available to provide transaction support. Table 13.17 Database Transaction Functions Function Description dataBeginTransaction data_begin_transaction Enters transaction mode with the given Manager. This mode is exited by calling either dataCommitTransaction or dataRoll- backTransaction. Arguments: Manager mgr—The Data manager to operate on. Returns: boolean—true = Successful transaction creation; false on failure. dataCommitTransaction data_commit_transaction Commits the current transaction and then exits transaction mode. A transaction must already have been started via dataBe- ginTransaction. Arguments: Manager mgr—DataSource manager under transaction. Returns: True on success or false on error. dataEndTransaction data_end_transaction Rolls back and ends the current transaction. No writes are per- sisted as part of the transaction. A transaction must already have been started via dataBeginTransaction. Arguments: Manager mgr—DataSource manager under transaction. Returns: True on success or false on error. dataIsInTransaction data_is_in_transaction Access function to determine if Data manager has an active transaction. Arguments: Manager mgr—DataSource manager to use. Returns: True if mgr is within a transaction. False otherwise. Download from www.wowebook.com ptg 346 Chapter 13 PHP in WebSphere sMash Table 13.17 Database Transaction Functions Function Description dataRollbackTransaction data_rollback_transaction Rollback the current transaction and then exits transaction mode. The caller should have called dataBeginTransaction before calling this API. Arguments: Manager mgr—Database manager holding active transaction. Returns: boolean—True on successful transaction rollback, or false on error. dataTransaction data_transaction Executes the given callback as a database transaction. If any errors occur, the entire transaction will be rolled back. The callback must accept two parameters: the DataSource man- ager, and an optional userData that is user defined (obviously), and handled by the callback function. Under normal circumstances, the callback is not required to return a value. However, there are two ways for the callback to explicitly fail the transaction. The callback can either throw an exception, or return false. If either of these occur, the transaction is rolled back; otherwise, it will be committed. Arguments: Manager mgr—DataSource manager to process the transaction. Callback callback—Function to process the full transaction data. Object userData—[Optional] User-defined parameter data to be passed into the callback function. Returns: boolean—True if the transaction completed and was properly committed. False otherwise. XML Utilities Extension name: zero.php.XMLExtension These functions provide simple access to XML data. This XML support is very limited, and its use beyond basic reading and writing of simple xML documents is discouraged. You should use the PHP built-in SimpleXML facilities. See the XML example later in this chapter. Download from www.wowebook.com ptg WebSphere sMash PHP Extensions 347 Conclusion PHP combined with WebSphere sMash forms an environment that is much more than the sum of its parts. PHP is an easily accessible web scripting language that promotes rapid development and short time to market. WebSphere sMash provides an excellent application server environ- ment with convenient and easy bridging between PHP and Java/Groovy. The combination of PHP and WebSphere sMash creates an outstanding web development environment, merging ease of use and enterprise-level power. Table 13.18 XML Utility Functions Function Description xml_decode Decodes an XML-encoded string into a SimpleXML-like object structure that can be processed using natural PHP conventions. Failures on decoding result in an XMLEncodingException. Arguments: XML string Returns: Object of decoded string. xml_encode Encodes an object into a string that represents a decodable XML object. Valid input includes primitive type and arrays. If invalid, input data will result in a XMLEncodingException. Parameters: Object key—The object to be XML encoded. Boolean idRefs—True will generate ID references for each node. False will not generate ID references. String xmlRoot—Value to use as the root element node for the XML docu- ment. Returns: XML string. getAttribute Returns the value of the attribute based on the provided key for an element. Arguments: String name—Name of attribute for this element. Returns: String value. getAttributes Return the complete array of attribute name value pairs on a given element. Returns: Array of key/value pairs. Download from www.wowebook.com ptg This page intentionally left blank Download from www.wowebook.com ptg 349 Groovy is an object-oriented, dynamically typed scripting language for Java developers. Java developers should feel comfortable using Groovy because it perpetuates Java’s syntax and semantics. Groovy also provides a more succinct syntax that results in code much smaller than comparable Java code. A developer can mix Java and Groovy style syntax, which allows Java developers to ease themselves into using Groovy style syntax. This chapter introduces you to the Groovy syntax to facilitate your understanding of Groovy code snippets throughout the text of this book. Before we dive into syntax, let’s start with a simple Java class that prints a message to stdout (standard out) and then rewrites it in a Groovy way (see Listing A.1). Listing A.1 Simple Java Class public class HelloGroovy { public static void main(String[] args) { System.out.println("Hello Groovy World!"); } } This code prints "Hello Groovy World!". This is perfectly acceptable Groovy code, but let’s refine it and make it as Groovy as possible. The first thing we can do to make this code more Groovy is to remove the class definition. We can also remove the special main method. Groovy has added println() to java.lang.Object, so there’s no need to have the System.out in front of it. A P P E N D I X A Get Started with Groovy Download from www.wowebook.com ptg 350 Appendix A Get Started with Groovy Groovy also makes semicolons and parentheses optional. Both can still be used, if needed—for example, if you wanted to put two statements on one line, you’d need to separate them with a semicolon. Taking all this into account, we end up with a Groovy script that looks like this: println "Hello Groovy World!" This code is compact with only the minimum needed to get the job done. There is a subtle difference between this Groovy code and the preceding Java code. The Groovy code is a script and is implicitly compiled to a class with the same name as the file in which the script is defined. You ca n se e thi s by add ing a lin e to y ou r sc rip t, as fo llows : println this.class Default Imports Groovy makes several packages available by default beyond the usual java.lang that Java imports by default. The result of these imports is that you can use many more classes without explicit imports. Listing A.2 shows the list of default imports for Groovy. Listing A.2 Default Imports import java.lang.* import java.util.* import java.io.* import java.net.* import java.math.BigInteger import java.math.BigDecimal import groovy.lang.* import groovy.util.* This gives the developer a wide variety of commonly used classes available by default. Dynamic Typing Groovy is a dynamically typed language. It does not require that you explicitly declare the type of a variable. Furthermore, variables can change types within your code (see Listing A.3). Listing A.3 Dynamic Variable Types class BarClass{ def var = "this is bar" } bar = new BarClass() println bar.var.class bar.var = 42 println bar.var.class Download from www.wowebook.com ptg GStrings and Heredocs 351 This code starts by defining a class named BarClass with a variable named var. Notice that the variable isn’t typed but uses the keyword def to define the variable. The output from this script shows us that the variable starts out as type java.lang.String and then becomes java.lang.Integer. This can be both helpful and frustrating, so you might want to be careful when naming your variables. You should also note that when you are writing a script and not a class, you can leave out the def keyword. In the preceding code, notice that the bar script variable is not typed, nor is it defined with the def keyword. This is perfectly acceptable Groovy code. However, using the def keyword can prove to be useful in avoiding erroneously reusing variable names. GStrings and Heredocs Groovy strings provide a method for string concatenation that is much easier than Java string concatenation. GStrings use embedded expressions to achieve this (see Listing A.4). Listing A.4 Embedded Expressions def pi = 3.1415 def foo = "PI equals $pi" This exemplifies the simplest use of GString expressions by using curly braces. We can do much more complicated expressions, however, as shown in Listing A.5. Listing A.5 More Embedded Expressions def pi = 3.1415 def foo = "2PI equals ${pi*2}" println "${foo.toUpperCase()}" We can also let our string span multiple lines with heredocs. In Groovy, heredocs are delim- ited with triple quotes (see Listing A.6). Listing A.6 Groovy Heredocs def pi = 3.1415 def foo = """This is a paragraph using Expressions like pi = $pi Spanning multiple lines.""" With GStrings and heredocs, Groovy provides a powerful set of string tools that are easy to use. Download from www.wowebook.com . to market. WebSphere sMash provides an excellent application server environ- ment with convenient and easy bridging between PHP and Java/Groovy. The combination of PHP and WebSphere sMash creates. simple xML documents is discouraged. You should use the PHP built-in SimpleXML facilities. See the XML example later in this chapter. Download from www.wowebook.com ptg WebSphere sMash PHP Extensions. 347 Conclusion PHP combined with WebSphere sMash forms an environment that is much more than the sum of its parts. PHP is an easily accessible web scripting language that promotes rapid development and