Here is a problem that many people have asked me how to do it. “Returning an array of string” with the code first approach. The API or WSDL generation annotation guide, http://wso2.org/project/wsf/php/2.0.0/docs/wsdl_generation_api.html contain all the things required in details. Here is an example of a service that return an array of string.

<?php

/** splitMe function
 * @param string $string_to_split string to split
 * (maps to the xs:string XML schema type )
 * @return array of string $result split to array
 *(maps to the xs:double XML schema type )
 */
function splitMe($string_to_split)
{
    return array("result" => split(":", $string_to_split));

}

$operations = array("splitMe"=>"splitMe");
$opParams = array("splitMe"=>"MIXED");

$svr = new WSService(array("operations"=>$operations,
                           "bindingStyle"=>"doclit",
                           "opParams"=>$opParams));

$svr->reply();
?>

Note that the annotation corresponding to the return value.

 * @return array of spring $result split to array

This will generate an schema with an element of maxOccurs=’unbounded’. Note that you can get the wsdl from the ’serviceurl?wsdl’.

<xsd:element name="splitMeResponse">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="result" maxOccurs="unbounded" type="xsd:string"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

Now just generate a client for this service using wsdl2php and try invoke it. You will get an array of string as the response.

    $input = new splitMe();
    $input->string_to_split = "a:b:c:d";

 
    // call the operation
    $response = $proxy->splitMe($input);
    print_r($response);

Now you can view the article I wrote titling “Introduction to PHP Data Services“. There I explain how you can design and implement Data Services in PHP using WSF/PHP Data Services Library.

This article covers,

  1. Designing your Data Service API.
  2. Writing the Data Service.
  3. Deploying and Testing Data Service.
  4. Make the Data Service available in both SOAP and RESTful form.
  5. Use of WS-* features in your Data Service.

If you are thinking of adapting SOA in to your database backed PHP applications, this article will be a good starting point.

PHP is one of the famous choice, when it comes to develop a web site. As the web evolve with the emerge of web service, REST (REpresentational State Transfer) concepts, the PHP language is also adapted to the new requirements specially with the availability of new SOA (Service Oriented Architecture), REST frameworks and libraries. Anyway there were hardly any guides, references or samples that properly describe the methodologies of developing REST applications using PHP.

The book “RESTful PHP Web Services‘ by Samisa Abeysinghe certainly fill this gap. It can be used as a step by step guideline for newbies to learn the concepts and write simple RESTful PHP applications and Mashups. And even experienced developers would find this a great reference to keep nearby while working with RESTful Web Services in PHP. And it has lot of code samples, utility functions that developers can use it in their applications.

RESTful PHP Web Services - Samisa Abeysinghe

About the Author

Samisa Abeysinghe is a well recognized name in the web services world. He lead the development of Apache Axis2/C and WSO2 WSF/PHP, two famous open source web service frameworks for ‘C’ and PHP. In addition to his deep knowledge in the subject, his experience in involving with the community and the enterprise for years and working as a lecturer in universities, should have influenced a lot in writing this book.

The Arrangement and the Content

The arrangement of the book is done really well to make sure the reader can go through it in the right sequence. All the content is bundled just within 200 pages. So you don’t need to allocate a lot of time to go through the whole book. It is organized into 7 chapters and two appendixes which are mostly independent from each other.

The first chapter is completely devoted to explain the concepts of RESTful web services. It basically explains what is RESTful web service and why it is needed. And it briefly mentions about the currently available REST Frameworks for PHP.

The second chapter introduce some PHP codes that do REST web service requests and handles the XML responses using both DOM and SimpleXML APIs. And in the third chapter it shows more code samples specially about consuming real world web services like BBC, Yahoo and an earthquakes information service. Theses codes are written as mashups mostly combining two services to produce more meaningful information.

The forth chapter is about  designing and writing web service providers. Its counterpart, writing web service consumers is described in the chapter five. There it demonstrate a library system that operate using RESTful webservices. You can map this example to any system that you may like to develop to run with RESTful web services. The chapter five of the book is available as a free download, RESTful PHP Web Services – Chapter 5.

The forth and fifth chapters are not using any framework to write the sample codes on consuming and providing web services. But in the sixth chapter it shows the use of Zend framework to do write them. There it rewrites the same example (The RESTful library system) in MVC (Model -View – Controller) approach using the functionalities of Zend framework. (In fact the View in the service is omitted).

The seventh chapter is about debugging web services. Debugging is a much needed step in any software development cycle. So if you are a newbie, you should read this chapter before start writing any of your own code. This introduces tools and methodologies to make your debugging easy and effective.

The book contains two appendixes. They are too really useful as the chapters of the book. In the first appendix it explains another REST web service framework, WSO2 Web Services Framework for PHP (WSF/PHP). To demonstrate it uses, some selected functionalities of the example library system (that is mentioned in chapters 4, 5, 6) is re-implemented using WSF/PHP. And it shows you how you can convert this RESTful system to a SOAP system in a minute. The second appendix provides you a code of a class (RESTClient), that you can use in consuming web services very effectively.

Recommended Readers

This book assume you have some knowledge in PHP. But it doesn’t require you to know anything related to web services, REST or XML. As you read the first few chapters, you will have a good understanding on the concepts and the basic applications of REST and XML using PHP. And the later chapters will guide to get deeper knowledge in writing complex and real world applications.

If you are a professional developer, you can skip the introduction chapters and jump directly to where you need to refer. For an example, if you use this book as a reference in designing and developing RESTful web service providers, you can directly read the chapter4 – Resource Oriented Services, chapter6- Resource Oriented Clients and Services with Zend Framework and probably the chapter 7 – Debugging Web Services.

This book contains the same example system (the library system) written in three different approaches, first without using any framework support, second using the Zend Framework, third using WSF/PHP. Each of them has its own pros and cons. So if you want to determine the approach more suitable to your requirements, or thinking of migrating from one to another, this book will be an ideal resource for you.

As you may have already noticed, this book contains lot of code samples. All the concepts are followed by simple code samples that explain the concept. In appendix it gives you a complete code for RESTClient class that you can use to call any REST service. Apart from the code of the example library system written using different frameworks, it has lot of codes for calling public web service APIs. And the explanation of the code is also done really well.

So it is clear this book is more targetting readers who like to implement PHP RESTful Systems in practice. And it covers enough concepts that you needed to know in writing practicle applications. So this book can take you from the zero knowlege to a deeper knowlege of RESTful PHP Web Services.

Same as web pages, web services also sometime require  client authentication. The most frequent way of authentication is the use of WS-Security Username token which authenticate clients based on the username and passwords. There can be situations where clients need to be authenticated based on its IP or its domain.

If you are writing web services from PHP (Using some PHP web service framework like WSF/PHP), You can use the PHP variables, $_SERVER["REMOTE_ADDR"] and $_SERVER["REMOTE_HOST"] to find the clients ip within the service logic code. If the client’s IP is static you can directly use the $_SERVER["REMOTE_ADDR"] and if it is dynamic you can use the $_SERVER["REMOTE_HOST"] which will be derived by reverse DNS look of the clients IP.

Here is one example of the use of these $_SERVER[] variables inside service logic.

 
function members_only_func($in_message) {

    // getting the clients IP.
    $remote_addr = $_SERVER["REMOTE_ADDR"];

    if($remote_addr == "67.205.26.154" ||
       $remote_addr == "124.43.59.95") {
       // generates the message for authenticated clients.

       return $valid_out_message;
    }

    // otherwise throw an exception
    throw new WSFault("Sender", "Failed to Authenticate");
}

$operations = array("membersOnlyOp" => "members_only_func");

$service = new WSService(array("operations" => $operations));

$service->reply();

December 18th, 2008Data Services Best Practices

In simple term, data services are exposing data as web services. Anyway it is not a complete definition. Actually there are situations where we use data services not only to read data, but also to create, update or delete data. So it is better say data services are doing CRUD (Create, Read, Update, Delete) operations for data through web services. Simply it is like providing a web service interface for the database.

Anyway exposing  a database directly as a web service is like violating the first principles of software engineering. It will tightly couple the database structure with the interface, so whenever you do a simple change to the database schema, you will have to change the web service interface which will no doubt break all the clients depending on it.

So first of all, you have to design the service interface independent of the database schema you have. Most of the time you will able to find some query that would map the service interface to the database schema.

For an example think of publishing data in database table (say for table name “Games”) like this.

Teams
GameID Venue Date Team1 Team2 Team1Score Team2Score
1 xxx stadium 2008-12-18 Italy Sweden 34 33
2 yyy stadium 2008-12-19 France Spain 51 50

You will directly able to map these data to data service. So the response payload for a “getGames” operation would be something like,

<getGamesResponse>
   <Game>
      <Venue>
         xxx stadium
      </Venue>
      <Date>
         2008-12-18
      </date>
      <Team1>
          Italy
      </Team1>
      <Team2>
          Sweden
      </Team2>
      <Team1Score>
          34
      </Team1Score>
      <Team2Score>
          33
      </Team2Score>
   </Game>
   <Game>
      <Venue>
         yyy stadium
      </Venue>
      <Date>
         2008-12-19
      </date>
      <Team1>
          France
      </Team1>
      <Team2>
          Spain
      </Team2>
      <Team1Score>
          51
      </Team1Score>
      <Team2Score>
          50
      </Team2Score>
   </Game>
</getGamesResponse>

You can get this done with a SQL query simply as this,

SELECT * FROM `Games`

Say later if you decided to restructure the database table so the new database schema would be like this,

Games
GameId Venue Date
1 xxx stadium 2008-12-18
1 yyy stadium 2008-12-19
GamesTeams
GameId TeamId score
1 1 70
1 2 33
2 1 51
2 3 50
Teams
TeamId Name Coach
1 Italy Mr. ABC
1 Canada Mr. PQR
2 Spain Mr. XYZ

(Note here the Games and Teams are associated in the GamesTeams table.)

You can still use a query like the one in following to provide the same service interface, because it returns the same result set as the earlier one.

   SELECT Games.Venue,
              Games.Date,
              Team1.Name AS Team1,
              Team2.Name AS Team2,
              GameTeam1.Score AS Score1,
              GameTeam2.Score AS Score2
         FROM Teams Team1,
              Teams Team2,
              GamesTeams GameTeam1,
              GamesTeams GameTeam2,
              Games
        WHERE GameTeam1.gameId = Games.gameId  AND
              GameTeam2.gameId = Games.gameId AND
              GameTeam1.teamId = Team1.teamId AND
              GameTeam2.teamId = Team2.teamId AND
              Team1.teamId <> Team2.teamId AND
              Team1.name=?

This allows you to keep the service interface unchanged, regardless of the changes you done to the database schema.

In addition to that, we can uses the features of the data service libraries to give meaningful names for the response elements. If we take above example itself, say you want to rename ‘Score1′ to ‘Team1-Score’ and ‘Score2′ to ‘Team2-Score’. But the dash character (‘-’) cannot be used as a variable in a database query. But you can provide that in the map of sql name to element name when you are writing the data service.

If you are using WSF/PHP php data services Here is how you provide that mapping,

$outputFormat = array("resultElement" => "getGamesResponse",
                      "rowElement" => "game",  // this is the repeating wrapper element for each game
                      "elements" => array( "Venue" => "Venue", // this is the mapping of xml name => sql name
                                           "Date" => "Date",
                                           "Team1" => "Team1",
                                           "Team2" => "Team2",
                                           "Team1-score" => "Score1", // we are using different names for sql and xml
                                           "Team2-score" => "Score2"));

If you write it using Java Data Services, you can use do this with the following configuration xml,

        <result element="getGamesResponse" rowName="game">
            <element name="Venue" column="Venu" />
            <element name="Date" column="Date" />
            <element name="Team1" column="Team1" />
            <element name="Team2" column="Team2" />
            <element name="Team1-Score" column="Score1" />
            <element name="Team2-Score" column="Score2" />
        </result>

Another consideration, when talking about the best practices of designing web services or data services is the granularity of the service interface. We say a web service is fine grained if the service contains tons of small operations. The opposite of that is the coarse grained services, which contains large but few operations. And it is recommended to use the later approach, you can see why from the following example.

Lets say you are developing a web service to upload some information. In order to upload the information first the user have to be authenticated and then the content should be validated. Then only he can submit the actual information. Say you design a fine grained web service for that. So it has three operations.

  1. authenticateUser
  2. validateContent
  3. submitInformation

If you design a coarse grained service interface it will be just the ‘uploadInformation’ operation. And all the three operation defined earlier will be called within the service logic and the clients will not be aware of that.

So here are some disadvantages that I see in the fine grained interface design compared with coarse grained design.

  1. The coupling is too high. Since the client is linked with the service in three adapters. Say you decided to change the service so that you first validate the content and depending on the content it sometime bypasses the authentication. You can’t do this with the former approach (fine grained approach) without changing the clients. But if it were designed as a coarse grained service (just one uploadInformation operation), the client need not to be changed.
  2. Two much time consumed for the transmission. Since we used three web service calls to do a single task the latency of the operation will largely depend on the network latency which will no doubt is comparatively very low. So the performance of the operation is degraded.
  3. The clients can bypass some steps!, Say in your fine grained service, some client bypass the authentication and validateContent steps and jump directly to the sumbitContent operation. In fact you have to write special code to make sure the clients call the service in the correct sequence, otherwise it will be a big security hole.

So I think these three points will be enough to explain why you should try to design a coarse grained interface for your web service.

You can apply these principle when you write data services as well. Lets take the same example explained above. Say there is another table that keep the scoring shots of each game like the one in following.

ScoringShots
GameID Time ScoringTeam ScoringPlayer

Here also you can keep the operation like ‘getGames’ which we defined in the above section. That operation only provide the basic information like the winner and the scores. So if the clients want to know about scoring shots as well, he have to call another operation, say getScoringShots(game) that will return the scoring shots results for a given game. If in practice the clients only need to know about scoring shots of few selected games, then this approach is ok.
But say normally clients need to know about the scoring shots of each and every games. Then they have to call the operation ‘getScoringShots’ multiple times. That’s when the lesson we just learn about the granularity can be applied. We can actually provide another operation, say ‘getGamesDetailed’ that actually bundle the details of scoring shots for all games with other information about the game. Here is snip of the response XML, I’m talking about.

<getGamesDetailedResponse>
   <Game>
      <Venue>
         xxx stadium
      </Venue>
      <Date>
         2008-12-18
      </date>
      <Team1>
          Italy
      </Team1>
      <Team2>
          Sweden
      </Team2>
      <Team1Score>
          34
      </Team1Score>
      <Team2Score>
          33
      </Team2Score>
      <!-- additionally we have ScoringShots element -->
      <ScoringShots>
          <Shot>
              <Time> xxx </Time>
              <ScoringPlayer> xxx </ScoringPlayer>
              <ScoringTeam> xxx </ScoringTeam>
              <Score> xxx </Score>
          </Shot>
          <Shot>
              <Time> yyy </Time>
              <ScoringPlayer> yyy </ScoringPlayer>
              <ScoringTeam> yyy </ScoringTeam>
              <Score> yyy </Score>
          </Shot>
      </ScoringShots>
   </Game>

   <Game>
    <!-- Another game details are mentioned here -->
   </Game>

   <!-- More Games -->
</getGamesDetailedResponse>

You can generate this kind of response using the nested query support of the data services libraries.
You can checkout more details about nested queries in php data services from my old post about php data service API.

LAMP (Linux + Apache + Mysql + PHP) stack powers many servers in the Internet today. For a LAMP  server, PostgreSQL could be the first alternative to Mysql. Similar to PHP + MySQL,  PHP + PostgreSQL too can be easily used in to host data services. Here are the steps to do it.

  1. If you already don’t have Apache + PHP + PostgreSQL download them from the following locations. Apache – http://httpd.apache.org/download.cgi, PHP – http://php.net and PostgreSQL – http://www.postgresql.org/download/
  2. You have to enable the PHP pdo_pgsql, pdo and pgsql plugins. Read here for the instructions to setup these libraries. (For an example: if you are windows you have to set the system ‘PATH’ variable to the <postgresql_installed_dir>/bin directory.
  3. If you already don’t have WSF/PHP, download and install it according to the guidelines provided in wsf/php installation guide.NOTE: You can check pdo_pgsql and wsf/php has properly installed with the help of phpinfo() function.
  4. Now lets start with creating a sample Database table. For this example I created a database called ‘workshop’, schema called ‘workshop’ and inside there the table ‘Employee’ with the following schema.
    Column Name Column Type
    employId integer
    name character varying
    email character varying
    jobTitle character varying
    project character varying

    Note: You can use phpPgAdmin (web based) or pgAdmin III to create tables from GUI

  5. Then you can write a small php script to expose the data in the above table as a web service.
    <?php
    
    //Including the Data Services library
    require_once("wso2/DataServices/DataService.php");
    
    // Including the connection information (i.e. PGSQUL USERNAME
    // and PGSQL_PASSWORD) for my PGSQL Connection
    require_once("constants.php");
    
    // database configurations
    $config = array(
    		"db" => "pgsql",
    		"username" => PGSQL_USERNAME,
    		"password" => PGSQL_PASSWORD,
    		"dbname" => "workshop",
    		"dbhost" => "localhost"
    		);
    
    $output_format = array(
                        "resultElement" => "employees",
                        "rowElement" => "employee",
                        "elements" => array(
    			    "id" => "employeeId",
                                "name" => "name",
                                "email" => "email",
                                "jobTitle" => "jobTitle",
                                "project" => "project"));
    
    $sql = "SELECT * FROM workshop.Employees";
    
    $get_employees_op = array("outputFormat" => $output_format, "sql" => $sql);
    
    $get_employees_url = array("HTTPMethod" => "GET", "RESTLocation" => "employees");
    
    // list of operations
    $operations = array(
                    "getEmployees" => $get_employees_op,
                    );
    
    // list of rest url mappping (operation => url)
    $restmap = array(
                    "getEmployees" => $get_employees_url,
                    );
    
    // creating DSService and reply
    $service = new DataService(array(
             "config" => $config,
             "operations" => $operations, "RESTMapping"=>$restmap));
    $service->reply();
    ?>
  6. We just wrote a PostgreSQL Data Services that provides its service as both REST and SOAP form. To deploy this service, We just need to copy this in to the web root directory. And the web URL for the script will be the endpoint to the web service.
  7. We can test the service either by calling its SOAP interface, which we may need to write a small SOAP client or by calling its REST interface, which only need a GET request from the browser. Say my script name is “my_dataservice.php” and I’ve put it in the web root directory, then the URL to call the REST interface of the service is
    http://localhost/my_dataservice.php/employees

WSDL Generation for PostgreSQL Data Service
You can get the WSDL for the service from the URL formed adding the suffix “?wsdl” (or “?wsdl2″ to wsdl v2.0) to the service URL,

http://localhost/my_dataservice.php?wsdl

Here all the schema data types are shown as xsd:anyType, which may not be the behavior that you want. In fact you can provide the schema data types to the fields from the code itself. Lets change the $outputFormat variable to provide the schema information as well using the following code snip.

$output_format = array(
                    "resultElement" => "employees",
                    "rowElement" => "employee",
                    "elements" => array(
			    "id" => array("column" => "employeeId",
		    			  "xsdType" => "xsd:int"),
			    "name" => array("column" => "name",
		    			  "xsdType" => "xsd:string"),
			    "email" => array("column" => "email",
		    			  "xsdType" => "xsd:string"),
			    "jobTitle" => array("column" => "jobTitle",
		    			  "xsdType" => "xsd:string"),
			    "project" => array("column" => "project",
		    			  "xsdType" => "xsd:string")));

Note that you provide the xsd type for each field explicitly. In fact this change is not needed for mysql pdo extension since it allows identifying field types programatically. Since this feature is not available in all the other pdo drivers, we have to explicitly give xsd type information for them.

If you wan to provide data services with SQLite or MSSQL, You can check my other posts on MSSQL(Microsoft SQL) Data Services In PHP and Data Services with SQLite in PHP.

With WSF/PHP Data Service library, you can convert a SQL query to a Data Service very easily in few steps.

  1. Decide your SQL query first, For the query you may require some input parameters, and you have to decide what should be returned by the query, Say your query is
    $sql_query = "SELECT name, age, email FROM users where country = ?";

    Then the “country” is our input parameter and the name, age, email are our return values.

  2. Define the input Format. For the above query it will be something like,
    $inputFormat = array("country" => "INT");
  3. Define the output format. We are giving the name “Users” for the out most wrapper element and the name “user” for the wrapper element of each user. Here is how we define it,
    $outputFormat = array("resultElement" => "users",
                    "rowElement" => "user",
                    "elements" => array(
                                "name" => "name",
                                "age" => "age",
                                "email" => "email"));

    For this output format, our expected result payload would be like,

    <users>
      <user>
         <name>xxx</name>
         <age>23</age>
         <email>xxx@xxx.xx</email>
      </user>
      <user>
         <name>yyy</name>
         <age>23</age>
         <email>yyy@yyy.yy</email>
      </user>
      ....
    </users>
  4. Define your operation using the sql query, input and output formats.
    $operations = array("getUsersByCountry" => array(
                                  "inputFormat" => $inputFormat,
                                  "sql" => $sql_query,
                                  "outputFormat" => $outputFormat));
  5. Define your database configuration in an array like this,
    $config = array(
        "db" => "mysql", // your db engine
        "username" => "myname", // name & password for the db server
        "password" => "mypasswd",
        "dbname" => "db", // the db
        "dbhost" => "localhost");
  6. Create a DataService instance using the database configuration and the operations we just created. And call DataServices reply method.
    $ds_service = new DataService(array(
                   "config" => $config,
                   "operations" => $operations));
    
    $ds_service->reply();

That is it. You just exposed your query as a web service. The PHP script URL will be the endpoint URL for the web service.

  1. WS-Addressing Action is used by web services to dispatch the operation for an incoming request SOAP message. It is one way of dispatching operations in WSF/PHP and it base Apach Axis2/C, other ways are SOAP action based dispatching which covers in my early blog “The Use of SOAP Action with WSF/PHP“,  Body based dispatching and URI based dispatching.
  2. In WSF/PHP client, we can enable the addressing by setting the “action” field in the request WSMessage instance and setting “useWSA”=> TRUE in the WSClient instance. Here is an example.
    $requestPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
       <text>Hello World!</text>
    </ns1:echoString>
    XML;
    
    $client = new WSClient(array("to" => "http://localhost/samples/echo_service.php",
                                 "useWSA" => TRUE));
    
    $requestMessage = new WSMessage($requestPayloadString,
    	    array("action" => "http://localhost/samples/echo_service/echoString"));
    
    $responseMessage = $client->request($requestMessage);
    
    printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

    If you doesn’t set “useWSA” => TRUE explicitly, the client will send the action as a SOAP action rather than a WSA Action. The above is the same example I used in demonstrating SOAP action with just the addition of “useWSA” option.

  3. You can select WS-Addressing version among “submission” which .NET support by default and “1.0″, just by mention it in the “useWSA” field.
    I.e.

    “useWSA” => “submission” Then the namespaces are having the values defined in the submission specification of WS-Addressing.
    “useWSA” => 1.0 Then the namespace are having the values defined in the WS-Addressing 1.0 spec.
  4. In the option “actions” in the WSService, we can provide the action to operation map, so the service will direct the SOAP messages to the correct operation by looking at the WS-Addressing action of the SOAP message.
    Here is a sample code that use action to dispatch the operation.

    function echoStringFunc($inMessage) {
        // logic of echoString operation
    }
    
    function echoIntFunc($inMessage) {
        // logic of echoInt operation
    }
    
    // we will take echoString and echoInt as tow operations
    $operations = array("echoString" => "echoStringFunction",
                        "echoInt" => "echoIntFunction");
    
    // soap action to operation map
    $actions = array("http://localhost/samples/echo_service/echoString" => "echoString",
                     "http://localhost/samples/echo_service/echoInt" => "echoInt");
    
    // creating the service with the operations and actions set
    $service = new WSService(array("operations" => $operations,
                                   "actions" => $actions));
    
    $service->reply();

    Note that this code is same as the code I post in a previous blog “The Use of SOAP Action with WSF/PHP” which uses SOAP action to dispatch the operation. In fact WSService will adjust to dispatch SOAP messages, so if there is a SOAP action in the message, it will be dispatched using that, and if it contains WS-Addressing action, it will used to do dispatching without the need of writing a single additional line of code. Note that this same code for both “submission” and “1.0″ WS-Addressing versions.

  5. In a WSDL 1.1, WS-Addressing action can be declared in the message element in the portType section.
        <wsdl:portType name="echoPortType">
            <wsdl:operation name="echoString">
                <wsdl:input message="ns0:echoStringRequest" wsaw:Action="http://localhost/samples/echo_service/echoString"/>
                <wsdl:output message="ns0:echoStringResponse" wsaw:Action="http://localhost/samples/echo_service/echoStringResponse"/>
            </wsdl:operation>
            <wsdl:operation name="echoInt">
                <wsdl:input message="ns0:echoIntRequest" wsaw:Action="http://localhost/samples/echo_service/echoInt"/>
                <wsdl:output message="ns0:echoIntResponse" wsaw:Action="http://localhost/samples/echo_service/echoIntResponse"/>
            </wsdl:operation>
        </wsdl:portType>

    When you use WSF/PHP in wsdl mode, it will pick the action declared in the WSDL and set it in the SOAP message, if you have enabled the addressing for the WSClient by setting non-null value for “useWSA” option.

In SOAP 1.1, the SOAP action is mentioned as a compulsory HTTP header. In practice it was used to identify the operation for a given request which we identify by the term ‘dispatching operations’.
As of SOAP 1.2, the SOAP action field became optional, and it was part of the content type header.

In WSF/PHP, you can use the “action” property of WSMessage to set the SOAP action in a request SOAP message.

$requestPayloadString = <<<XML
<ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
   <text>Hello World!</text>
</ns1:echoString>
XML;

$client = new WSClient(array( "to" => "http://localhost/samples/echo_service.php" ));

$requestMessage = new WSMessage($requestPayloadString,
	    array("action" => "http://localhost/samples/echo_service/echoString"));

$responseMessage = $client->request($requestMessage);

printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

WSF/PHP send SOAP 1.2 request by default. So the SOAP message HTTP headers for the above code would be like this,

POST /samples/echo_service.php HTTP/1.1
User-Agent: Axis2C/1.5.0
Content-Length: 223
Content-Type: application/soap+xml;charset=UTF-8;action="http://localhost/samples/echo_service/echoString"
Host: 127.0.0.1

Note that the SOAP  Action is sent in the Content-Type inside the optional action parameter.

If you set it to use SOAP 1.1 explicitly in the WSClient like this,

$client = new WSClient(array( "to" => "http://localhost/samples/echo_service.php",
                              "useSOAP" => 1.1 ));

It would send the SOAP Action as a separate HTTP header,

POST /samples/echo_service.php HTTP/1.1
User-Agent: Axis2C/1.5.0
SOAPAction: "http://localhost/samples/echo_service/echoString"
Content-Length: 225
Content-Type: text/xml;charset=UTF-8
Host: 127.0.0.1

If you are using WSF/PHP in the server side, you don’t need to worry about the SOAP version as it will support both SOAP 1.1 and SOAP 1.2 automatically.
Anyway you need to declared the actions to operations map, so WSF/PHP will be able to dispatch the SOAP request and direct the message to the correct operation.

function echoStringFunc($inMessage) {
    // logic of echoString operation
}

function echoIntFunc($inMessage) {
    // logic of echoInt operation
}

// we will take echoString and echoInt as tow operations
$operations = array("echoString" => "echoStringFunction",
                    "echoInt" => "echoIntFunction");

// soap action to operation map
$actions = array("http://localhost/samples/echo_service/echoString" => "echoString",
                 "http://localhost/samples/echo_service/echoInt" => "echoInt");

// creating the service with the operations and actions set
$service = new WSService(array("operations" => $operations,
                               "actions" => $actions));

$service->reply();

So whenever a SOAP request message hit this script, it will check the SOAPAction HTTP header if it is a SOAP 1.1 message, or the action parameter in the Content-Type HTTP header if it is 1.2, then try to find the function mapped with that action from the actions map.
Anyway if the SOAP action is not set in the request message WSF/PHP will try to dispatch the message with other methods like body based dispatching, WS-Addressing based dispatching which are transport protocol independent dispatching mechanisms.

Anyway since most of the cases SOAP is used on top of HTTP, it is really common SOAP messages are dispatched using the SOAP action which is no doubt a very easy and efficient way of dispatching.

Database plays a big role in any day-today application. It is a major component from accounting, web portal, CMS, SaaS applications, search engines to all enterprise applications. In traditional MVC(Model-View-Controller) applications we talk about the Model component which represent the database.. And in 3-tier architectural pattern it is the ‘Data layer’ which represent the database and provide data to the ‘Logic Layer’ as per request.

As SOA evolves, database is becoming just one part of the ‘Data Layer’ or the ‘Model’ component. There are many data sources, data providers which are mostly deployed as web services which you can ask for data as you do with traditional databases. This gives you the advantages of the use of web services like interoperability, security and reliability and other WS-* support. And it helps you to get rid of the headache of installing different drivers for different databases and most importantly it removes the tight binding of your application to the database. So with adaption of SOA, the ‘Data Layer’ has been replaced by the ‘Service Consuming Layer’.

The story of the ‘Data Provider’ also changed with the SOA adaption. The new data sources are designed with the SOA in mind. And the legacy systems are wrapped by a service layer to make it more easier to consume. We use the term ‘Data Services’ for the data sources deployed as web services.

There are many public data services available as ‘REST’ which is a lighter way of providing services. The other way is the use of WS-* features like WS-Security, WS-Reliable Messaging to deploy the data services which are mostly adopted by the enterprise.

Today there are many tools around, that helps you to develop data services from existing databases. WSO2 provides an open source data service framework that allows you to build data services from simple xml configuration files without the need of writing a single line of code. And WSF/PHP also packed with a data services library that allow you to write a simple PHP script to build a data service.

PHP is one of the favorite language to write database back-ended web applications. Specially considering the fact that there are thousands of servers powered by the LAMP (Linux  + Apache + MySQL +PHP) stack, PHP data service library would comes useful to build around a web service around these existing data sources and make them SOA-aware.


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