As many of other languages, XML schema too have data types. Basically it can be categorized in to two groups.

  1. Simple Types
  2. Complex Types

The different between these 2 types are so easy to identify. Say you have a schema element with a simple type like this.

<xs:element name="xx" type="someSimpleType"/>

Then a possible xml to validate against this schema is

<xx>Bingo</x>

Inside the ‘xxx’ you can only find texts, But in a case of a  schema element with complex types,

<xs:element name="xx" type="someComplexType"/>

The XML will be set of nested elements.

<xx>
  <yy>hi</yy>
  <zz>Nested elements</zz>
</xx>

Simply complex type contains elements with simple types or complex types similar to the class types in OOP languages which contain member variables with different types.

But unlike most of the other languages, in schema simple types are not always primitive types. There can be user derived simple types as well.

I will talk about each of these variations in schema types and their PHP representation of WSDL2PHP tool.

  • Primitive Types & Built-in Types
  • List Types
  • Union Types
  • Faceted Types

Primitive Types & Built-in Types

The XML schema specification talks about 19 primitive types. Some of the common of these simple types and the corresponding PHP types generated by WSDL2PHP tool are,

Schema Type PHP Type
string string
boolean boolean
decimal float
float float
double double
duration string
dateTime string (from above wsf/php 2.0 it is an integer – representing timestamp)

You may have noticed the famous types like ‘integer’, ‘byte’, ‘short’ are missing out of the above list. In fact these types exist, but they are not primitive types. They are derived from decimal (special cases when the fraction digits are 0 :) . Anyway still these types are considered built-in types in xml schema. Here is the complete list of built-in types (both primitive and non-primitive built-in types)

‘integer’, ‘byte’ and ‘short’ are mapped to PHP integer types by the WSDL2PHP tool.

To show an example how WSDL2PHP tool generating code for simple types, I will take the following schema Element.

<xs:element name="myName" type="xs:string"/>

And WSDL2PHP will generate a simple public variable (Assuming this is generating inside some class) for that element with a comment to describing it.

    /**
     * @var string
     */
     public $myName;

So if I specified some value for the variable (Taking the variable name of the parent class is $parent),

$parent->myName = "James";

I will get the following nice XML.

<myName>James</myName>

This is the same approach for all the other built-in types as well.

List Types

The list types are derived from list of simple types. It still a simple type because it list all the element in the list as a white-space separated text inside the parent element.

Here is how you may declare a list type in an xml schema.

<xs:simpleType name="mylist">
    <xs:list itemType="xs:int"/>
</xs:simpleType>

<!-- example element to have the above list value -->
<xs:element name="xCoordinates" type="tns:mylist"/>

Then the WSDL2PHP generated PHP code would be something like,

    /**
     * @var array of int
     */
    public $xCoordinates;

As the comment implies, you have to feed the values in an php array.

$parent->xCoordinates = array(1, 3, 8, 7, 9);

And Here is the XML you are getting,

<xCoordinates>1 3 8 7 9</xCoordinates>

Similarly you can have list of any simple types regardless whether it is built-in or derived.

Union Types

The union in schema is similar to the unions in ‘C’. In C variables of a union can have one (and not more than one) of the types declared inside the union type. Similarly in schema elements with union types can have one and only one simple type among the member types declared in the union. Here is an example of declaring union type,

<xs:simpleType name="myIntStringUnion">
    <xs:union memberTypes="xs:int xs:string"/>
</xs:simpleType>

<!-- example element to have the above union value -->
<xs:element name="garbage" type="tns:myIntStringUnion"/>

And the WSDl2PHP generated code,

    /**
     * @var int/string
     */
    public $garbage;

So if you read the comment you can have an idea that this variable accept either ‘in’ or ‘string’ type without digging in to the WSDL.

Faceted Types

You can apply facets and restrict the value space of a simple type.

  • length
  • minLength
  • maxLength
  • pattern
  • enumeration
  • whiteSpace
  • maxInclusive
  • maxExclusive
  • minExclusive
  • minInclusive
  • totalDigits
  • fractionDigits

Some facets are specific to some built-in data types or types derived from these built-in datatypes. Here is a table of valid facets for each of the above mentioned catagory of types.

I have earlier blogged about how you work on faceted types in PHP in the post “Coding Schema Inheritance in PHP“. So Here I will list out a similar example  to demonstrate the PHP generated code by WSDL2PHP tool for facets.

Here is a schema with the ‘enumeration’ facet.

<!-- applying enumeration facet to the xs:string -->
<xs:simpleType name="mySubject">
    <xs:restriction base="xs:string">
         <xs:enumeration value="Maths"/>
         <xs:enumeration value="Physics"/>
         <xs:enumeration value="Chemistry"/>
    </xs:restriction>
</xs:simpleType>

<!-- example element to have the above faceted value -->
<xs:element name="subject" type="tns:mySubject"/>

And here is the WSDL2PHP generated code,

    /**
     * @var string
     *     NOTE: subject should follow the following restrictions
     *     You can have one of the following value
     *     Maths
     *     Physics
     *     Chemistry
     */
    public $subject;

It clearly says your variable ‘subject’ is only allowed to have the list of values mentioned in the ‘enumeration’.

So I just wrote about some variations of simple schema types and how they are represented in the WSDL2PHP generated code. As you may have observed, you don’t need to know any thing about the WSDL or the schema to write a PHP code around that, since WSDL2PHP gives you a generated code mentioning all the guidelines, restrictions about using them.

In XML Schema we declare an array or a multiple occurrence of a schema element by setting its maxOccurs attribute to a value greater than 1 or to the value “unbounded” in a case of no maximum boundary.

<xs:element maxOccurs="unbounded"
            minOccurs="0"
            name="params"
            nillable="true"
            type="xs:int"/>

If you generate PHP code to such a schema using wsdl2php tool, you will get a code for the class variable named “params” similar to this.

    /**
     * @var array[0, unbounded] of int
     */
    public $params;

So if you have a variable (say $object) for the object of this class you can fill the “params” field like this,

$object->params = array(1, 5, 8);

This will create the xml with the expected array of elements.

<wrapper>
    <params>1</params>
    <params>5</params>
    <params>8</params>
</wrapper>

Not only for simple types, you can have arrays of complex types too.

<xs:element maxOccurs="unbounded"
            minOccurs="0"
            name="params"
            nillable="true"
            type="tns:MyComplexType"/>

Instead of giving simple integers like earlier case, this time you will feed the “params” variable with an array of PHP objects of ‘MyComplexType’ class.

$obj1 = new MyComplexType();
/* feeding data to obj1 variables */

$obj2 = new MyComplexType();
/* feeding data to obj2 variables */

$obj3 = new MyComplexType();
/* feeding data to obj3 variables */

$object->params = array($obj1, $obj2, $obj3);

This will create a xml containing array of params similar to this,

<wrapper>
    <params>
        <elementx/> <!-- elements in the MyComplexType type -->
        <elementy/>
    </params>
    <params>
        ... <!-- elements in the MyComplexType type -->
    </params>
    <params>
        ... <!-- elements in the MyComplexType type -->
    </params>
</wrapper>

If you are thinking of writing a web service or a client based on a WSDL, you can easily generate the code for PHP or any other language using tools likes wsdl2php or other wsdl2xxx category tools. Then you don’t need to really worry about what is the schema of the WSDL or any other finer details. But sometime it may useful to know how different schema constructs are generated in PHP level so you can have a good idea when you are using them. This post describes How inheritance is used in XML Schema and how it is mapped to PHP code from wsdl2php tool in WSF/PHP.

There are several ways that one schema type can inherit another type.  Here are some names use to refer them.

  • SimpleType Restriction – Forming simple type by restricting another simple type
  • SimpleContent Extension – Forming complex type by extending a simple type
  • ComplexContent Extension – Forming complex type by extending another complex type

Note that here the word ‘type’ always refers to a schema type.

It is not straight forward to do a one to one map from these schema structures to a PHP or some other language. But wsdl2php tool does that keeping the simplicity and preserving the original meaning. Lets see how it is done for each of the above mentioned methods of inheriting.

SimpleType Restriction

You can create a simple type by restricting some values of another simple type. Here is an example.

            <!-- derivedType from applying
              simple type restriction for xs:string -->
            <xs:simpleType name="derivedType">
                <xs:restriction base="xs:string">
                    <xs:enumeration value="a"/>
                    <xs:enumeration value="ab"/>
                    <xs:enumeration value="abc"/>
                    <xs:enumeration value="abcd"/>
                </xs:restriction>
            </xs:simpleType>

Here the derivedType is a string, but it can only have values “a”, “ab”, “abc” and “abcd”. This restriction have used the “enumeration” (which we call a facet) to restrict the possible values. You can use other facets like length, minLength, MaxLength and so on. Here are the complete list of facets in the schema specification.

So lets see hows this is mapped to a PHP code. Here we assume this type is used in an schema element called ‘input’.

    /**
     * @var string
     *     NOTE: $input should follow the following restrictions
     *     You can have one of the following value
     *     a
     *     ab
     *     abc
     *     abcd
     */
     public $input;

Note that here it does not say anything about the ‘derivedType’. Rather it says it is of type “String” which is a PHP type and in addition it has some restrictions, or rules when assigning values.

Although it could have been possible to use getters and setters to impose these rules, this uses just a comment about the rules because this way it is really easy the use the variable.

Say we have another type (say derievedType2) restricting the ‘derievedType’, that type will have the combination of restrictions of both types.

Here is the xml schema representation of the ‘derievedType2′.

            <!-- derivedType2-->
            <xs:simpleType name="derivedType2">
                <xs:restriction base="tns:derivedType">
                    <xs:maxLength value="3"/>
                    <xs:minLength value="2"/>
                </xs:restriction>
            </xs:simpleType>

And if input2 have that type, the php code will look like this, (Note that it has the combination of rules).

    /**
     * @var string
     *     NOTE: $input2 should follow the following restrictions
     *     You can have one of the following value
     *     a
     *     ab
     *     abc
     *     abcd
     *     Your length of the value should be
     *     Greater than 2
     *     Less than 3
     */
     public $input2;

I have highlighted the additional rules compared with $input, so you can see the difference.

SimpleContent Extension

Simple Content extension is extending a simple type to make a complex type. Say we have an element (say with the name “mystring”) and it has “xs:string” simple type.

<xs:element name="mystring" type="xs:string"/>

And here is a valid xml with this schema.

<mystring>this can contain only string</mystring>

So if I say I’m going to make a complex type extending this simple type you may think that I’m going to add element in to that. In fact I will create a complex type by adding an attribute.

<mystring myint="3">this can contain only string</mystring>

The schema to this xml will be something like this. (Note that I have assumed there is an schema element named “mystring” with the type “myStringType”)

            <xs:complexType name="myStringType">
                <xs:simpleContent>
                    <xs:extension base="xs:string">
                        <xs:attribute name="myint" type="xs:int"/>
                    </xs:extension>
                </xs:simpleContent>
            </xs:complexType>

The PHP generated code for this schema is something like this,

class myStringType {

    /**
     * @var int
     */
    public $myint;

    // The "value" represents the element 'myStringType' value..

    /**
     * @var string
     */
    public $value;

}

So as you can see it creates a PHP class for that schema type with member variables for each attributes and finally for the value of the parent type. So in order to represent the above mentioned xml, you will use the following PHP code.

$type = new myStringType();

$type->myint = 3;
$type->value = "this can contain only string";

Next we will look at the inheritance with complexContent Extension.

ComplexContent Extension

This is to create a complex type by inheriting another complexType.

            <!-- the parent type -->
            <xs:complexType name="parentType">
                <xs:sequence>
                    <xs:element name="demo3" type="xs:int"/>
                    <xs:element name="demo4" type="xs:string"/>
                </xs:sequence>
            </xs:complexType>

            <!-- the child type -->
            <xs:complexType name="childType">
                <xs:complexContent>
                    <xs:extension base="tns:parentType">
                        <xs:sequence>
                            <xs:element name="demo1" type="xs:int"/>
                            <xs:element name="demo2" type="xs:string"/>
                        </xs:sequence>
                    </xs:extension>
                </xs:complexContent>
            </xs:complexType>

So here the childType will inherit the ‘demo3′ and ‘demo4′ elements from the parent type. We will see how is the PHP generated code looks like.

class parentType {

    /**
     * @var int
     */
    public $demo3;

    /**
     * @var string
     */
    public $demo4;

}

class childType extends parentType {

    /**
     * @var int
     */
    public $demo1;

    /**
     * @var string
     */
    public $demo2;

}

It has uses the PHP inheritance to reprensent the schema inheritance. And the nice thing is you can use the childType for the places you have to use the parentType.  That is the theoy we learn at the inheritance class of other languages (Java, C++) too.

So say there is another complexType (say “anotherChildType”) inheriting from the type “parentType” and one another complexType (say “nextLevelChildType”) inheriting this time from “childType” (which in fact inheriting from the “parentType” as mentioned above).

So our types tree would be something like this.

--- parentType
         |
         +-------- childType
         |              |
         |              +------------- nexLevelChildType
         |
         +-------- anotherChildType

And lets say there is a schema element called ‘input3′ with the type parentType. Then the generated variable for the input3 element will be like following code segment.

    /**
     * @var (object)parentType
     *    Or one of following derived class(es)
     *       childType
     *       nextLevelChildType
     *       anotherChildType
     */
    public $input3;

This comment tells you that you can actually use the inherited types in place of the parent type according to your preferences.

PHP Web Services Demo Site contains a set of nice tools that help development of web services in PHP.

  • WSDL2PHP tool – This allow you to generate PHP code for your WSDL. Note that this need your wsdl to be in a URL that it can access.
  • PHP2WSDL tool – Here you can paste your annotated PHP code and get the WSDL (both version 1.1 and 2.0) generated.  You can find the annotation syntax in here.
  • DBS2PHP tool – WSO2 has Data Services library implemented in both Java and PHP. In Java Data Services you give the configuration via an XML (in .dbs extension). Whereas in PHP you give the configuration via a simple PHP code which use arrays to feed the configuration parameters. If you are more familiar in writing XML than PHP, you can first write the XML and then convert it to PHP using DBS2PHP tool.

September 21st, 2008WSDL2PHP 2 Minutes Introduction

WSDL2PHP makes the development of web service providers and consumers quick and easy. I wrote a 2 minutes guide on developing web services providers sometimes ago. So lets concentrate on developing web service consumers here.

Where is WSDL2PHP?

WSDL2PHP script is included in the WSF/PHP packs. You can find the wsdl2php.php script inside the ‘scripts’ directory of any source or binary package. Or you can use the online wsd2php tool hosted in WSF/PHP web services DEMO Site.

How to Run the Script?

Here is the command

/scripts/wsdl2php.php mywsdl.wsdl > myclient.php

The Code is Generated. How Can I add My Code There?

It is simple. Just search for the comment “//TODO”.
Check for an example here.

You have to write custom code for 2 occasions per operation.

  1. To Provide Input Parameters
  2. To Handle output parameters.

An Example?

Here is the code snippet corresponding to the simpleAdd request for our demo WSDL.

    $input = new simpleAdd();
    //TODO: fill in the class fields of $input to match your business logic

    // call the operation
    $response = $proxy->simpleAdd($input);
    //TODO: Implement business logic to consume $response, which is of type simpleAddResponse

Here is how after I filled my logic in place of TODO comments.

    $input = new simpleAdd();
    //DONE: fill in the class fields of $input to match your business logic

    //-------my code----
    $input->param0 = 2;
    $input->param1 = 3;
    //------------------

    // call the operation
    $response = $proxy->simpleAdd($input);
    //DONE: Implement business logic to consume $response, which is of type simpleAddResponse

    //--------my code-----
    echo $response->return;
    //--------------------

WSF/PHP allows you to develop web services with both Contract First (Starting from WSDL) and Code First Approaches. From these two, Contract First approach is the most famous and most recomended way of developing a Webservice. There you need to have a WSDL to start with. I will take the http://labs.wso2.org/wsf/php/example.xml as our WSDL.

Generate The Service Code

When you download the WSF/PHP pack there is a script called ‘wsdl2php.php’ in the script directory. Open a command line and run it with the following options. Or you can use the online wsdl2php tool

php wsdl2php.php http://labs.wso2.org/wsf/php/example.xml -s

Complete The Business Logic

Complete the TODO section of the generated file. Apparently what is left to do is filling the business logic for each function corresponding to the service operations in your WSDL. You are given the hint to the input and output parameters. Here is how I fill the logic for the simpleAdd function.

function simpleAdd($input) {
    // TODO: fill in the business logic
    // NOTE: $input is of type simpleAdd
    // NOTE: should return an object of type simpleAddResponse

    $res = new simpleAddResponse();

    $res->return = $input->param0 + $input->param1;

    return $res;
}

Advanced Types? – Read Generated Hints for Class variables

So how about filling the matrix add logic. Can be it be really complex?. No, what you need to observe is there the class member variables contains not only simple types but also another Class type. There is a comment on each member variables to hint its type. So the logic for the matrix addition is simple as this,

function matrixAdd($input) {
    // TODO: fill in the business logic
    // NOTE: $input is of type matrixAdd
    // NOTE: should return an object of type matrixAddResponse

    $matrix0 = $input->param0;
    $matrix1 = $input->param1;

    $matrix2 = new Matrix();
    $matrix2->rows = array();

    if(count($matrix0->rows) == count($matrix1->rows)) { // considering only happy path

        for($i = 0; $i < count($matrix0->rows); $i ++ ) {

            $row0 = $matrix0->rows[$i];
            $row1 = $matrix1->rows[$i];

            $row2 = new MatrixRow();
            $matrix2->rows[] = $row2;
            $row2->columns = array();

            if(count($row0->columns) == count($row1->columns)) {

                for($j = 0; $j< count($row0->columns); $j ++ ) {

                    $col0 = $row0->columns[$j];
                    $col1 = $row1->columns[$j];

                    $col2 = $col0 + $col1;

                    $row2->columns[] = $col2;
                }
            }
        }
    }

    $res = new matrixAddResponse();
    $res->return = $matrix2;
    return $res;
}

© 2007 Dimuthu’s Blog | iKon Wordpress Theme by Windows Vista Administration | Powered by Wordpress