Saturday, January 19, 2008

Mapping WSDL schema elements to PHP Classes

Since I talked about how you can deal with WSDLs using WSF/PHP in last two days, I thought of blogging a kind of a hidden feature of WSF/PHP related to WSDLs today.

When you are using WSF/PHP wsdl mode API in the client side, you can use classes to hold your data. That is simply you will be filling data in your class like you are creating an XML.

For an example,
<HelloWorld>
<name>Hiro</name>
</HelloWorld>
would map to the following PHP class,
class HelloWorld
{
public $name;
}
I will take the yesterdays (and the same used in day before yesterday) WSDL to explain a full example of use of this feature..


<?php

/*
* Client.php
*/


/* Class HelloWorld maps to the following schema part
* <xsd:element name="HelloWorld">
* <xsd:complexType>
* <xsd:sequence>
* <xsd:element name="name" type="xsd:string"/>
* </xsd:sequence>
* </xsd:complexType>
* </xsd:element>
*/


class HelloWorld
{
public $name;
}

/* Class HelloWordResponse maps to the following schema part
* <xsd:element name="HelloWorldResponse">
* <xsd:complexType>
* <xsd:sequence>
* <xsd:element name="return" type="xsd:string"/>
* </xsd:sequence>
* </xsd:complexType>
* </xsd:element>

*/

class HelloWorldResponse
{
public $return;
}

/*
* Additionally you have to create the class map
* (i.e. Schema element => PHP Class Name
*/



$class_map = array("HelloWorld"=> "HelloWorld",
"HelloWorldResponse"=> "HelloWorldResponse");



/* create the WSClient with the given WSDL and my service endpoint
Note: Here im overwriting the endpoint declared in the WSDL */

$wsclient = new WSClient( array(
"classmap" => $class_map,
"wsdl" => "http://localhost/Service_wsdl.php?wsdl"));


/* we need to take the proxy object to call the wsdl operation */
$proxy = $wsclient->getProxy();

/* prepare the input */

$input = new HelloWorld();


$input->name = "Hiro";

/* Right here I'm calling the HelloWorld function with
* argument as the HelloWorld instance
* Remeber in the WSDL we had "HelloWorld"
* operation with name argument */

$ret_val = $proxy->HelloWorld($input);


/* Retrive the response. Just to recall,
* our response is an instance of HelloWorldResponse */

echo $ret_val->return."\n";

?>

No comments: