Payload Problems? WSF/PHP to the Rescue!

Thursday, January 31, 2008

I am seeing numerous users having payload problems with native SOAP extension and NuSOAP, specially when inter-operating with heterogeneous systems.

The best solution is to use WSF/PHP, the Web services framework with XML in-out model in the heart of its implementation, thanks to Apache Axis2/C.

As PHP users, we would be comfortable working with our own data types such as arrays and classes, and let the SOAP engine handle the serialization completely. WSF/PHP is gradually going there. However, in the mean time, if you run into XML request format problems with other implementations such as .NET, Java, etc. you can always use XML mode.

If you consider native PHP SOAP extension, there is no way to trap the XML payload and manipulate it, and some of the serialization behaviors could not be fine tuned at all. But with WSF/PHP, you can, and it is also written in C. So you have the speed that you want over NuSOAP. I have seen users asking on tweaking XML payload format with NuSOAP as well.

Payload the Way You Want with PHP5 built-in SOAP

Wednesday, January 30, 2008

Say you want this payload:

        <ns1:base>
            <itemsLine xsi:type="ns2:urn:test">
               <name xsi:type="xsd:string">A</name>
               <type xsi:type="xsd:string">D</type>
               <from xsi:type="xsd:string">C</from>
               <fluke xsi:type="xsd:string">D</fluke>
            </itemsLine>
            <itemsLine xsi:type="ns2:urn:test">
               <name xsi:type="xsd:string">E</name>
               <type xsi:type="xsd:string">H</type>
               <from xsi:type="xsd:string">G</from>
               <fluke xsi:type="xsd:string">H</fluke>
            </itemsLine>
         </ns1:base>

 

How do you get this XML to be output by the SoapClient?

You can get this exact payload with the following code:

<?php
class itemsLine{
    function itemsLine($a, $b, $c, $d)
    {
        $this->name = $a;
        $this->type = $d;
        $this->from = $c;
        $this->fluke = $d;
    }
}

$client = new SoapClient(null, array('location' => "http://localhost:9090/soap.php",
                                     'uri'      => "http://test-uri/"));
$item1 = new itemsLine('A', 'B', 'C', 'D');
$item2 = new itemsLine('E', 'F', 'G', 'H');

$var1 = new SoapVar($item1 , SOAP_ENC_OBJECT, "urn:test", "http://soapinterop.org/xsd");
$var2 = new SoapVar($item2 , SOAP_ENC_OBJECT, "urn:test", "http://soapinterop.org/xsd");

$client->base(new SoapParam($var1, "itemsLine"), new SoapParam($var2, "itemsLine"));
?>

Amazon Online Shopping with Web Service Framework for PHP

Tuesday, January 29, 2008

I wrote an article on "Amazon Online Shopping with Web Service Framework for PHP" for Oxygen Tank.

There I'm demonstrating how to write a simple client library to access Amazon Web Services and how to use that library to write your own application to do online shopping with Amazon.com

There I attached the Client library code and two sample applications, one very simple php command line application and the other much improved web application. Hope this will be useful to people who are interested in working with WSF/PHP.

Hello World Clients with PHP

Yesterday I gave you the sources for the services. Here are the Web service clients.

With SOAP Extension:
<?php   
$client = new SoapClient(null, array('location' => "http://localhost:9090/soap_ext/hw_service.php",
'uri' => "http://test-uri/"));
$result =  $client->__soapCall('hello', array('name' => 'Sam'));
printf($result);
?>

With NuSOAP:
<?php
require_once('../lib/nusoap.php');
$client = new soapclient('http://localhost:9090/nusoap-0.7.3/samples/hw_service.php');
$result = $client->call('hello', array('name' => 'Sam'));
printf($result);
?>

With WSF/PHP:
<?php   
$reqestPayloadString = <<<XML
<hello>
<name>Sam</name>
</hello>

XML;
$client = new WSClient(array("to" => "http://localhost:9090/tutorial/hello/hw_service.php"));   
$response = $client->request($reqestPayloadString);   
$simplexml = new SimpleXMLElement($response->str);
$result = $simplexml->return[0];   
printf($result);   
?>  

Hello World Service with PHP SOAP Extension, NuSOAP and WSF/PHP

Monday, January 28, 2008

With SOAP extension:
<?php

function
hello($param) {
$retval = 'Hello, '.$param;
return $retval;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction('hello');
$server->handle();
?>

With NuSOAP:
<?php
require_once('../lib/nusoap.php');

$server
= new soap_server;
$server->register('hello');

function
hello($name) {
return 'Hello, ' . $name;
}

$HTTP_RAW_POST_DATA
= isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>

With WSF/PHP:
<?php   

function
hello($message) {

$simplexml = new SimpleXMLElement($message->str);
$name = $simplexml->name[0];

$responsePayloadString = <<<XML
<helloResponse>
<return>Hello, $name</return>
</helloResponse>

XML;

return
$responsePayloadString;
}

$service
= new WSService(array("operations" => array("hello")));
$service->reply();
?>

Realities of SOA

Sunday, January 27, 2008

In a previous entry, I discussed the importance of PHP users being serious about SOA. In there, I mentioned that SOA is real and here to stay. You may be interested in knowing the realities of SOA as at the start of 2008. That blog entry summarizes the mistakes and success as far as adoption of SOA is concerned.

I think that 2008 would be a critical year for SOA, with many people applying the enterprise architecture style in their IT systems.

Form this list of predictions for 2008:

This is the year that Service Oriented Architectures (SOA) moves from IT strategy to business strategy. Therefore, SOA will officially move out of the hype cycle and into mainstream. CEOs and CIOs have bought into the importance of consistent business oriented services. Therefore, expect that customers will get down to serious business of moving out of pilots into slow, deliberate implementations. This doesn’t make for splashy headlines but it does make business sense.

It would be good to learn form others mistakes and capitalize on the success factors. In my opinion, most of the mistakes could be avoided by understanding the importance of the A in SOA.

Cannot Run NuSOAP and SOAP Extension Together?

Saturday, January 26, 2008

I was trying to run both NuSOAP and SOAP ext together using the same Apache instance, but NuSOAP seems to fail when SOAP extension is enabled.

Both of them run fine when WSF/PHP is enabled. I am not sure if this is my own problem or a common problem.

You still like RPC-Enc style WSDLs

Friday, January 25, 2008

RPC-Encoded is a WSDL style you find in the WSDL 1.1 spec. For some reason in WSDL 2 (fortunately) these style concept of WSDL has been thrown away and only the Document literal style has been survive. So now RPC-Encoded is kind of a deprecated style.

I think there are two main reason that made RPC-Encoded not to use anymore.

First is as first part of its name (RPC stands for Remote Procedure Call) imply this is used to do remote procedure call through network. This lead to appear lot of fine grained services which do just very simple function call through the network. This violates a kind of principal (or just a best practice) of web services, that is you should design a coarse grained fixed interface for a web services. So this was -1 for RPC and +10000 for Document style WSDLs.

Second reason for its failure is the second part of its name, the encoding mechanism. It uses soap encoding which is really tedious to implement, (In fact I am thinking of doing an implementation for Axis2/C, but it seems not that straight forward) And it seems different implementations are hard to inter-operate with this encoding. This made WS-I to prohibit use of RPC-ENC and promote doc-lit.

Anyway we can see still there are many people who ask for RPC-Enc style wsdl support. I think this is because of the legacy systems they are using.

Web Service Framework for PHP
also has great support on DOC-Lit style than RPC-ENC. But still It is a good tools for legacy system developers, since it gives the basic functionalities like dynamic-invocation and wsdl-generation with the RPC-Enoded wsdl s as well.

Data Services with PHP

What if we could expose a Database as a Web service? That would be appealing for users to access data with ease, across systems. We can use PHP WS framework to get this job done, with a bit of design. We have been doing just that in the last few days and implementing a demo. We should be able to host it for the benefit of the users soon.

More on this soon....

NuSOAP Feature List

Thursday, January 24, 2008

I was looking for a feature list of NuSOAP. I could not find any. There is a chengelog file that comes with the source zip package, but that does not list the features as such.

The documentation zip package too does not mention anything on the current set of features, only the API docs are there.

The project page mentions:

It is a set of PHP classes - no PHP extensions required - that allow developers to create and consume web services based on SOAP 1.1, WSDL 1.1 and HTTP 1.0/1.1.

One of these days I will compose one to see just what it offers at a high level for the benefit of the new users.

What is Missing in PHP SOAP Extension?

Wednesday, January 23, 2008

Couple of days back, I blogged about the features of SOAP extension. Now, are these features good enough. Yes they sure are for simple SOAP services.

However, simple SOAP services draws much criticism, specially form REST fans. If you want to do only simple stuff with SOAP, why not use REST? I see that to be a valid argument, especially in the PHP world, given that HTTP is the dominant transport.

In fact, the real value of SOAP comes, when things get complex, more enterprise in nature. That is where the QoS comes into play. SOAP is not that much useful, when you want to use the Fliker upload images, you of course and use the REST API. SOAP is useful when you want to send an invoice, that contains special discounted rates, securely to one of your customers. You have to be absolutely sure that only that customer sees it. And may be you are using a spread sheet or a PDF file to record the invoice and you want to send it as it is. This requires the need to send binary attachment with security with SOAP. And if you are lucky, your customer's system too would use PHP, however, in this heterogeneous world, it may well be that the customer is on .NET or using J2EE.  In short, you need a interoperable comprehensive SOAP stack.

PHP SOAP extension is good to get started, to play around with. However, it falls much short in meeting the enterprise demands in the SOA era.

Can you improve it, to support security and binary attachments? Of course you can. However, the concern is that the time it would take to make it interop side by side with .NET and Java implementations. They have taken years to come to that stage. I have seen how much effort has been spent on Apache Axis2/Java and Apache Axis2/C. Even if you have people with right expertise, WS-Security alone would take at least two person years to complete.

It is the WSDL mode that most users love to use. And if you ever have worked with a WSDL tool, you know how hectic it is to support all the user scenarios. Specially the schema support is an endless game. Most of the interop issues pop up with WSDLs. WSDL mode in SOAP extension already have enough interop issues. And there are no plans to support WSDL 2.0. Let alone, the most critical feature to support in WSDL is the WS-Policy support. Specially when WS-Security in in use, the security policies are the way of conveying rules of the level of security to be used and the rules to follow. Even if basic WS-Security is implemented based on some library like xmlsec, supporting policies would require a WS-Policy processing engine. That too will require at least one person year of work.

In summary, it would be years before serious Web services could be implemented with PHP SOAP extension. Web services are complex!

Where to set your options?.. in WSClient or in WSMessage?

If you are familiar with WSF/PHP web service API, you may find that you can set your options in different level in your code . For an example when you are writing a web service client, you can set the same options set in the WSClient constructor or in the WSMessage constructor.

I wrote a blog with my ideas on how to select the right place to set the options in order to have well designed and efficient web service client.

Spread the Word

Tuesday, January 22, 2008

The feed of this blog was removed from planet PHP today. There was some reaction on the early content being too much on WSO2 stuff. Then there seemed to be this idea that this blog is too much on Web services stuff.

The original purpose of this blog is to be a dedicated one for Web services with PHP. I think it would be good to stay focused on that, because, there seemed to be some good readership on the content.

I always believe that in the near future, the average PHP user would have to deal with SOA aspects much more than they used to be. So my expectation is that this blog would help those users to get a grasp of what SOA has to offer.

Despite the fact that this blog would no longer appear on planet PHP, if you who is reading this right now feel the content is of use, spread the word about this blog.

REST with PHP - More Tips

Monday, January 21, 2008

Earlier, I mentioned how CURL API could be used to do REST with PHP. There is a blog entry by Dimuthu on PHP Web services with fopen. This further shows how to use the PHP functions you are already familiar with to consume Web services in REST style.

Dimuthu has also shown how to do SOAP with fopen, however, I believe it is better to use a framework when using SOAP, because more often than not, SOAP is used when QoS is required, and it would be too tedious to coin all SOAP syntax manually with QoS headers in place.

PHP SOAP Extension Feature List

I was searching the Web for $subject, and did not have much luck. May be I did not search right, anyway...

So I thought of compiling a feature list, based on what I know:

  • SOAP
    • Support for SOAP 1.1 and SOAP 1.2
    • Ability to map SOAP fault to exceptions, so that you can try/catch
    • SOAP header handling capability
    • Message tracing capability on client side. Last request and last response could be accessed.
  • WSDL
    • Support for WSDL 1.1
    • WSDL mode (Technically, in Web services world this is known as contract first model. Contract is the WSDL. You use a given WSDL to write either services and/or clients)
  • Non-WSDL mode
    • Both services and clients could be implemented without having a WSDL to start with
  • Data binding
    • When using WSDL mode, can use a class map to define the mapping between XML schemas in WSDL to PHP classes
  • Transports
    • Obviously HTTP, HTTP raw post data
    • Can use HTTP authentication mechanisms
    • And also HTTPS
  • WS-*
    • Can use SOAP header class to add any headers corresponding to a Web services specification
  • Interoperability
    • Moderate. Works with .NET and Java to some extent

 

And some observations:

  • Packaging
    • Is a PHP extension
    • Comes bundled with PHP5
  • License
    • PHP license
  • Written in
    • C programming language, ground up
    • Deemed to be faster than PHP based implementations such as NuSOAP
  • Documentation
  • Maintenance
    • Bugs are fixed regularly
    • No major feature additions lately

REST with PHP

Sunday, January 20, 2008

The simplest form of REST with PHP comes with XML + CURL. PHP can use the features available within the language to send and receive data, preferably in XML format in case of Web services, over HTTP. One of the most popular techniques is to use the CURL API and GET or POST contents to a URL. This naturally maps to the REST principles. This model is for client side, for consuming services.

For server side, going by the REST principles, one could argue, any hosted PHP script could be considered a REST service. Again, for the sake of Web services, to enable machine to machine interactions, rather than machine to human, XML would be the preferred form of input and output in case of a service. Again, nothing fancy is required, other than the current set of PHP API and extensions.

In short, REST with PHP is pretty simple.

PHP Web Services: Getting Started

Friday, January 18, 2008

From the article on PHP Web Services:

Service Oriented Architecture (SOA) is popular in the enterprise, as it simplifies connecting systems. One of the preferred technologies used to implement SOA is Web services, other contenders being traditional messaging systems and plain old XML (POX) techniques. Web services technologies are capable of enabling machine-to-machine interactions, ensuring interoperability among heterogeneous systems. This helps realize loose coupling, a key characteristic of SOA. The machine processable interface, defined using WSDL, message based interactions, using SOAP, and the use of other Web related standards such as HTTP and XML, are the key pillars on which Web services are built.

Given the importance of Web services in the SOA era, it is a must that any programming language has provision to leverage the power of this technology and be able to play its role in a SOA implementation. PHP too has several options when it comes to working with Web services, however, one of the problems till recently was that the level of support for Web services in PHP was limited to SOAP interactions with some level of WSDL coverage. There was hardly any support for the full Web services stack, including addressing, binary attachments and security.

Dolphin in the Sun

Wednesday, January 16, 2008

It is ironic, that just a day after I blogged about about M in LAMP going to be replaced with S, the announcement came that Sun is acquiring MySQL. However, I did not mean to say Sun, but rather S in SOA.

Now it would be interesting to see how many would stick to MySQL and keep the LAMP burning, despite the dawn of the Sun, and how many would look for alternatives such as Postgresql and put off lamp for LAPP (or better yet LAPS).

The Need for WS-Security

Yesterday, I wrote about the why we should bother about SOA as PHP users. When we talk about enterprise, security comes to center stage. When you use message passing, with SOA setups, the sensitive messages would have to be secured.

With PHP, there is a well known way of securing client to server communication, that is https. So when talking about REST, one may say, we can use https and secure the messages. True, but is that good enough? For some classes of applications, yes it would. However, many enterprise applications may not be satisfied with that level of security. If you have doubts on this, talk to a security experts. Well, I am not one of those security geeks, but I sure have spoken to few. They would say, the "intruder" could be anywhere.

I borrowed the following image form this article on WSE.

 

At the top, it shows how a protocol-level security such as https could secure your application. The moment the message is delivers, the plain message gets exposed. The "intruder" can easily sneak a peek into the message. As I mentioned earlier, this could be acceptable for some applications, but not all.

The ideal security is the level of security shown in the bottom half of the image, where the message itself is secured. May be the message is signed or encrypted, and sometimes both. Now this cannot done only with transport security like https. You have to secure the message itself. WS-Security specification is meant for just this. It defines how to secure the message itself. So if you want this level of security, you need SOAP Web services. And there are applications, specially enterprise applications that need this level of security.

The good news is that, like Java and .NET, PHP too has full implementation of WS-Security powered by Apache Rampart/C. If you want more information, you can read this article on secure web services with PHP.

Now, one would be wondering, do people really use WS-Security in enterprise applications? Yes they do, and I have seen them. I have seen gaming systems, betting systems and government document transfer systems use WS-Security.  And more often than not, these systems are heterogeneous. They had .NET, Java and yes PHP. I am yet to see a PHP Web service that uses WS-Security in practice, but I sure have seen PHP consuming Web services that enforce security policies implemented in .NET or Java in real world.

Why PHP Users should be Serious about SOA?

Tuesday, January 15, 2008

PHP is a scripting language, as we all know. The initial purpose was to help Web programmers to build the dynamic web pages, to ease the mess of programming for the dynamic content. Then PHP nicely hooked up with Apache Web server and MySQL. With the rise of Linux, came LAMP, tough P may be said to represent Perl, Python as well as Ruby - the new kind on the block (well, actually then it should be called LAMR), for many, the first thing that comes to mind with P in LAMP is PHP. (The same is true for WAMP as well). The lighting of LAMP gave rise to a new era of applications. PHP gradually evolved form the scripting language that used to ease the generation of dynamic Web pages to a programming language that runs enterprise applications.

Gradually, PHP became a main contender in the enterprise space, playing a role side by side with Java and Microsoft .NET technologies. In addition to the open source presence in many fronts, starting form the php.net downloads to packaged solutions like XAMPP and WampServer, companies like Zend offering enterprise grade products and support, has further strengthened the position of PHP in enterprise applications.

If you look at most of the applications few years ago, and even today, there is a database component. Hence the M in LAMP. The interesting question is, would M hold on to its position in LAMP for the long run, or would it have to let S in SOA to come to that place?

SOA has been a buzz word a few years ago, may be two to three years ago. That was the peak of hype on SOA - in my feeling Ruby and to some extent REST is at the top of the hype right now. By now, hype on SOA has dies down. And many software architects would agree that SOA as an architectural style that is here to stay. It is a fact that, because SOA simplifies connecting systems though loose coupling, almost all enterprise applications would have at lease some elements of SOA within them.

SOA, as a principle, has been there for many years. Hence there have been many traditional technologies, as an example some custom messaging systems, that could be used to realize SOA. However, the rise of Web services brought the SOA term into light and injected new life into it. Both SOAP (or WS-* as some call it) as well as REST could be used to realize SOA with relative eaze. I would not jump into that heated argument on SOAP vs. REST here. However, I must mention that neither WS-* nor REST should be completely ignored, when you think about enterprise applications.

PHP users used to be closely working with Databases. However, looking at the trends, it looks like, more often than not, we would have to talk to services rather than to databases in the future applications. SOA is not full fledged in terms of adoption as of yet. But it is happening. Many businesses and many enterprise applications are in the process of laying out the infrastructure for SOA. Hence, PHP being a programming language increasingly used for enterprise applications would have to consume and provide more services more often than it used to.

It used to be LAMP or WAMP; It is only a matter of time before they become LASP or WASP, where S is for Services. Are you ready to change gears?

WSF/PHP with XAMPP, WampServer, Zend Core and Lighttpd

Monday, January 14, 2008

Web services framework for PHP has been tested with PHP5, Zend Core 2.5, WampServer2, XAMPP 1.6.4 and Lithttpd.

Nandika has explained how to get Web services working for XAMPP for Windows. An illustrated guide on installing with XAMPP is also available. Similar set of steps would get the WSF/PHP Windows binary working wit WampServer2.

Mohanjith has explained how he got WSF/PHP working with Lighthttpd. And Nandika has also explained how to get the pecl package working.

You can download the source and binaries from the download page and try out yourself.

SOAP Versions with SoapClient and WSClient

Saturday, January 12, 2008

With the PHP SOAP extension, you can use an option in the SoapClient constructor and set the SOAP version to be used.

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => http://test-uri/,
'soap_version' => SOAP_1_2));

The above code sets SOAP 1.2 as the SOAP version to be used. The API document does not mention the default version used in case the user does not provide 'soap_version'. If you want SOAP 1.1, then use 'soap_version' => SOAP_1_1

With the PHP Web services framework, like in the case of SoapClient, you can use the WSClient constructor options to set the SOAP version to be used.

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


The above code sets SOAP 1.1 as the SOAP version to be used. As the API document mentions, the default SOAP version used is SOAP 1.2, in case the user does not provide useSOAP option.



Interestingly, "useSOAP" => FALSE can be used as well.


$client = new WSClient(array("to" => http://localhost/tutorial/soap/service.php,


"useSOAP" => FALSE));

This means, instead of sending a SOAP message, send the payload given to the client as Plain Old XML. You can consider this to be a form of REST invocation.

WSDL with NuSOAP

Thursday, January 10, 2008

Yesterday I blogged about the WSDL generation capabilities of PHP Web services framework.

I found this article on NuSOAP WSDL support. Basically the article describes the WSDL mode equivalent supported by NuSOAP.

NuSOAP as well as WSO2 WSF/PHP are open source projects. NuSOAP comes with LGPL license and is implemented in PHP. WSO2 WSF/PHP is written in C and comes with the Apache 2.0 license.

PHP5 SOAP Extension

I wrote this article sometime back on the PHP5 SOAP extension. It details the classes of extension, two implementation models of Web services, and also lists a 'Hello World with SOAP Extension'.

If you want to compare and contrast PHP5 SOAP extension with WSO2's Web services framework, you can have a look into this article.

WSDL Generation with PHP

WSDL is the key for sharing the service interface. Some people call this the 'contract'. Sometimes, developers have access to an already written WSDL. So they can use that and generate either the client code or the service code or both. This is called the 'contract first model'. Sometimes, what we have is a PHP script, and we want to expose that as a service. In that case, we have the code and we would like to generate the WSDL. This approach is called the 'code first model'.

WSDL generation is supported with WSO2 Web Services Framework for PHP and is done using PHP reflection and an annotation parser. To generate a WSDL from a given PHP Web service, a ?wsdl request should be sent to the server. For example, if you want to generate the WSDL for the service echoService.php, a request should be sent as,

http://localhost/services/echoService.php?wsdl

This will generate a WSDL that adheres to 1.1 specification. You can also generate WSDL 2.0, you can use ?wsdl2 in place of ?wsdl.

For more details, you can refer tot he WSDL generation API documentation.

Convert your PHP script to a Web Service

Web Services are not only for Java and .net people. WSO2 WSF/PHP allows you to easily explore your PHP script as a web service. You may have written a nice PHP script may be to access a MYSQL database. Then why not published it as a web service ? The advantage is using WSO2 WSF/PHP you can explore the script functionality as Web service operations to non PHP clients may be written in .NET, Java or in any other language. Don't worry WSO2 WSF/PHP guarantees the interoperability.

Deploy your PHP class as a Webservice

With the new WSO2 WSF/PHP 1.2 you can publish PHP classes as a web service.

You are able to publish multiple PHP classes as a web service. Then your PHP code for the WSService would be something like this..


/* set operations and constructor arguments for the class1 */

$class1_operations = array("service_operation" => "php_class_function_in_class1",
/* and so on..*/);


$class1_constructor_arguments = array("arg1", "arg2", /* and so on..*/);

/* set operations and constructor arguments for the class2 */


$class2_operations = array("service_operation" => "php_class_function_in_class2",
/* and so on..*/);

$class2_constructor_arguments = array("arg1", "arg2", /* and so on..*/);


/* set these in to the classes option of the WSService in following way */

new WSService(array("classes" => array(

"class1_name" => array("operations" => $class1_operations, "args"=> $class1_constructor_arguments),
"class2_name" => array("operations" => $class2_operations, "args"=> $class2_constructor_arguments) ) ) );

Visit here for a good sample of an application of this feature..

Sending Attachments with PHP Web Services

Wednesday, January 9, 2008

WSO2 WSF/PHP supports sending binary attachments with SOAP messages with SOAP MTOM implementation. WSO2 WSF/PHP is equipped with both optimized and non optimized binary attachments. You can upload or down load attachments with both optimized or non optimized methods.It is really simple .First download WSF/PHP.Go to samples/mtom. It contains all the magic you need to do this in PHP.

Debugging and Troubleshooting PHP Services and Clients

Users sometimes would run into trouble at two stages when getting the PHP Web services extension working.

First the challenge is to get it installed. How can you check if it is working? Well, first, you can check with the phpinfo() function. If the extension is correctly installed, you will get an entry for the extension, with the name wsf. And a table following the wsf  title, you would see a table with 'wsf support' 'enabled' entries. That will be followed by the table displaying hte php.ini directives for WSO2 WSF/PHP extension. If this entry is missing form the phpinfo() page, that means the extension is not properly loaded.

If the extension does not seem to appear with phpinfo(), you can double check your PATH variable to verify that the required dlls are on the PATH as mentioned by the install guide. More often than not, the extension fails to load due to PATH problems, when it cannot find the required libraries.

When you get it installed, the second form of problems come when you cannot seem to get the samples working. Again there are some settings to double check. First the php.ini entries. Often, users happen to enter setting where the file locations, such as login path, pointed to by the php.ini entries are either non existent or do not have write access. Also check if your include_path setting in the php.ini file includes the scripts folder that comes with the PHP distribution.

When all the above are correct and still things are not working, you can turn to log files written by the Web services extension. Logs are written into the folder pointed by the wsf.log_path entry that you add to the php.ini file. If this is not set, the default location is /tmp. Note that, on Microsoft Windows, the default folder may not exist, hence you must set the wsf.log_path setting in php.ini. Logs related to the services are written to a file named wsf_php_server.log and client logs are written to a file named wsf_php_client.log. You can vary the level of information written to the logs by changing the wsf.log_level entry that you add to the php.ini file.

In case you want to verify that the messages are sent and received by the clients and services and that those messages are of the desired format, you can use the SOAP message tracing techniques that I discussed yesterday.

Deploying PHP Web Services using XAMPP for windows

If you are interested in using XAMPP to develop web services using WSF/PHP, here is an install guide to get you started.

Approaches you can select in developing your PHP Web Service

When you start writing a Webservice you will have to choose one of the two popular approaches of developing a Webservice, i.e. code-first approach or contract-first approach.

In code first approach, initially you will code the interfaces you want to publish as the web service even with the business logic inside. Then you generate WSDL which become the contract (at least the major part of the contract) based on the written code.

Whereas In contract-first approach, you first start with writing the WSDL and then you generate codes for the programming language to provide and consume the service. From these two approaches you need to selectively choose the best one for you based on your problem environment. You may find some good explanation of this topic by Ajith Ranabahu in here.

WSO2 Web Service Framework for PHP
give you the maximum support for both kind of approaches.

If you already have written the service code and deployed it, you can get generated the WSDL by just adding "?wsdl" to the end of service URI. That is for the people who uses code-first approach.

If you already have the WSDL, then you will be able to use the WSDL mode API to write the service enabling the contract-first approach. This really minimize the effort and time you have to spend in writing a service, although it is encouraged to use the XML in/out mode API, which no doubt gives you more performance.

PHP Web Services Training

Tuesday, January 8, 2008

PHP Web Services – Get Real with Enterprise SOA is an online training offered by WSO2 on PHP Web services.

Covers all the key topics including WSDL generation, WSDL mode, binary attachments and security features such as signing encryption.

Make your PHP Webservice available for both REST and SOAP consumers

You may have noticed many public web services have deployed their services both as REST services and SOAP services, (e.g. Flickr). You may like to have this feature in your services as well. If you are working with WSO2 Web Service Framework for PHP you don't need to worry about this. Because its engine itself take care of publishing your service both in REST and SOAP form.

In fact one of the indirect advantage, I experienced from this feature is, it allows us to test our Webservice logic in much easier path.

For an example think you are a teacher in a high school and you want to publish examination results through a Webservice.

1 <?php
2 /* exam.php: Simple PHP Webservice for publish students marks */
3
4 /* getResults: This is the operation you going to expose as the Webservice operaion */
5 function getResults($message) {
6
7 /* you hard code the results in an array */
8
9 $results_map = array("Hiro" => "A+",
10 "Clair" => "A+",
11 "Peter" => "A+",
12 "Mohinder" => "A+",
13 "Ando" => "A",
14 "Niki" => "B",
15 "Sylar" => "F",
16 /* you are not worrying to put others results, since they all have 'F's */);
17
18 /* extract the firstName using SimpleXML techniques */
19
20 $xml = new SimpleXMLElement($message->str);
21 $firstName = trim($xml->firstName);
22
23
24 /* you look for the result for the firstName */
25 $result = $results_map[firstName];
26 if($result === NULL)
27 {
28 /* sorry I dont have time to give you a good result.. :( */
29 $result = "F";
30 }
31
32 /* build the response xml and return */
33 return "<result>$result</result>";
34
35 }
36
37 /* create a WSService and specify the service operation */
38 $service = new WSService(array("operations" => array("getResults")));
39
40 $service->reply();
41
42 ?>

So you are done writing and deploying the service by copying it to the Apache Root directory. But you may feel little lazy to write a simple client to test this service. Although it is very simple to write a client (either SOAP or REST) with WSF/PHP, much easier way is to simply open a browser and type following text in the address bar.

"http://mysubject.myhighschool.edu/exam.php/getResults?firstName=Hiro (That is add the the "exam.php/getResults?firstName=Hiro" to the URL where you have hosted your service)

If you see something like

<result>A+</result>

you are done. You can continue testing your service by typing several names and observing whether it returns the correct one.

Actually what you have done here is sending a 'REST' request to the service. If this is working fine your logic is correct. And it will work for the 'SOAP' request as well.

So availability of the services both in REST and SOAP form is a cool feature in WSO2 Webservice framework for PHP which is really helpful not only for consumers but also for service developers.

Tracing SOAP Messages

With WSO2 Web services framework for PHP, you can trace the SOAP messages that are sent and received by the client.

The Web services client class, WSClient has two methods for this, getLastRequest() and getLastResponse().

After calling the request() method of the client instance, you can call any of those methods to gain access to the messages.

 

$response = $client->request($reqestPayloadString);

printf("<br/> Request = %s </br>", htmlspecialchars($client->getLastRequest()));

printf("<br/> Response = %s </br>", htmlspecialchars($client->getLastResponse()));

 

The above code fragment would display the request and the response messages that were sent and received as a result of the call to the request() method.

An example output would look something like:

Request = <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Header/><soapenv:Body><getFactorial> <param>6</param> </getFactorial></soapenv:Body></soapenv:Envelope>
Response = <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Header/><soapenv:Body><getFactorialResponse> <result>720</result> </getFactorialResponse></soapenv:Body></soapenv:Envelope>

 

Tracing of SOAP messages in relation to a service invocation is useful specially when troubleshooting services and clients.

Using pecl tool to install WSF/PHP

If you are interested in using pecl tool to install WSF/PHP here is a step wise guide.

Dealing with Payloads

Monday, January 7, 2008

Last week, I talked about getting a simple service and client working. However, these samples did not dig into the details of dealing with the payload.

Payload is the business logic specific content sent within the SOAP body of the SOAP message. Let us look into a sample where a number is given to calculate the factorial. The client sends the number and the service calculates the factorial and returns the result.

Here is the payload that the client sends:

<getFactorial>
    <param>6</param>
</getFactorial>

 

Now the service needs to understand the incoming payload and pick the param to calculate the result. Here is the code for the operation:

  1. function getFactorial($message) {

  2.  

  3. $simplexml = new SimpleXMLElement($message->str);

  4. $value = $simplexml->param[0];

  5.  

  6. $result = factorial($value);

  7.  

  8. $responsePayloadString = <<<XML

  9. <getFactorialResponse>

  10. <result>$result</result>

  11. </getFactorialResponse>

  12. XML;

  13.  

  14. return $responsePayloadString;

  15. }

On line 3, we create a SimpleXMLElement instance, using the incoming payload. Line 4 access the param value within the payload. This means that the service needs to have some understanding about the format of the incoming payload in order to process it. The rest of the logic in the function implementing the operation is simple. On line 6, factorial is calculated for the incoming param value and form line 8 to 12, the response payload is prepared with the result. Finally on line 14, we return the response payload.

The response payload would look something like:

<getFactorialResponse>

        <result>720</result>

</getFactorialResponse>

The client too can process the response payload in a way similar to how it was done on server side.

  1. $response = $client->request($reqestPayloadString);

  2.  

  3. $simplexml = new SimpleXMLElement($response->str);

  4.  

  5. echo "Result = ".$simplexml->result[0]."\n";

Create SimpleXMLElement instance out of the response and access the result element.

Now you know how to deal with incoming payloads both on client as well as on server side.

The Best Practices of using WSClient

If you are accessing Webservice in your application, the best practice is to delegate your Webservice accessing aspects to a separate class. This way you can hide the Webservice consumer layer from the rest of the application.

When you are using WSClient in WSO2 Web Service Framework for PHP, you can do this by defining a separate class which extend the WSClient. For an example think about a simple Webservice for ScoreBoard which gives the total score of a Cricket match. Then you will write a PHP class which completely interact with the Service.


  1 <?php
2
3 class ScoreBoardClient extends WSClient
4 {
5 // Constructor of the new Client
6 public function __construct() {
7 parent::__construct(array( "to" => "scoreboard.sports.org"));
8 }
9
10 // The service operation of getting Total Score
11 // You can provide the match number and the team name
12 public function getTotalScore($match_no, $team) {
13
14 $xml = <<< XML
15 <GetTotalScore>
16 <match>{$match_no}</match>
17 <team>{$team}</team>
18 </GetTotalScore>
19 XML;
20 try
21 {
22 $res = $this->request($xml);
23 }
24 catch(Exception $e)
25 {
26 // Handle the exception..
27 return -1;
28 }
29 // For the clarity I ignore the response xml processing part
30 return $res->str;
31
32 }

33 }
34
35 ?>


  • The PHP Class: (lines 3 -33) - The ScoreBoarClient PHP class which extends the WSClient.
  • The constructor: (lines 6-8) - This calls the WSClient constructor (the parent of the ScoreBoardClient class) with options, in this case only the service endpoint. If you are intending to use WS-Security, you may initialize the service policies here.
  • The Service operation wrapper (lines 12-32) - This is where you do all the Webservice accesing stuffs like building the request payload(lines 14-19), calling the remote service (lines22), and return the result to the caller.

So lets see how the application call the service using this class.


01 $my_scoreboard = new ScoreBoardClient();
02
03 $total_score = $my_scoreboard->getTotalScore(5, "Sri Lanka");
04
05 echo "Total Score is: $total_score \n";
06


It s simple as we are calling another local function. If you like to see more example which follow this pattern, just go to the script/wso2 directory of the WSO2 WSF/PHP distribution and observe how amazon, flickr and yahoo webservices are wrapped with PHP Classes.

Secure Web services in PHP

Do you want to do secure web services in PHP ? Then no choice other than WSF/PHP . You can taste all the security features in a very cool way.

.NET and PHP Talking

Sunday, January 6, 2008

Can a .NET application talk to a PHP application? Can a PHP application talk to a .NET application? Yes for both cases. But, how? Well there could be multiple ways, but the most obvious answer is with Web services.

Ok, so I can use PHP5 SOAP extension and get the job done? Yes to some extent. With PHP5 SOAP extension you can get started. However, if you use WSO2 Web services framework for PHP, you can do more.

Do more in the sense? In addition to SOAP, you can get .NET and PHP to exchange binary data attachments as well as secure messages that are signed or encrypted or both.

In short, they are interoperable.

Most Exciting Features of Upcoming WSO2 WSF/PHP Release

Saturday, January 5, 2008

We have packed and tested WSO2 Web services framework version 1.2.0. Release note will go out next Monday.

I am very excited about this release. The key features to look out for are:

  • WSDL generation
    • We have improved the code first model a great deal. This release will have the greatest WSDL generation capabilities that the PHP world has ever seen
  • WSDL Mode improvements
    • Now you can provide a WSDL with security policies and the framework is capable of dealing with those policies and enforce them
  • Class mapping support for services
    • So far we only supported exposing PHP functions as Web service operations. This release has added support to expose the member functions of a PHP class as service operations
  • We also have provided Windows and Linux binaries of the framework that that would work with Zend Core

As always, it is open source (Apache license) and free to download and use as you wish. Download now and enjoy these excitements!!!

REST with PHP

Friday, January 4, 2008

If you are a REST fan, you may frown upon SOAP. However, in my humble opinion, you should not. They are more complementary than contending.

Web services framework for PHP has that vision too. That is why, apart form being a strong WS-* framework, it also supports REST.

The key feature that I like with WSO2 WSF/PHP is that, a single service can be exposed both as REST as well as SOAP service. You write one code and the engine would take care of the rest (or should I say REST ;) )

Use of WSMessage in PHP Web Services

Thursday, January 3, 2008

In a Web services invocation, there are two messages involved, for two way operations. One is the request message and the other is the response message. WSMessage class in the Web services framework for PHP is used to represent these messages.

The str member variable of the WSMessage class can hold the the message content, termed as payload, as an XML string.

If you are sending a request, form a client, you can fill in the request WSMessage instance with the XML payload and send it. The received response payload will be stored in a WSMessage instance as an XML string and returned to client.

If you are receiving a request, form a service, the received request payload will be contained in a WSMessage instance. You can process the request, prepare the response, store it in a WSMessage instance and return that instance.

WSMessage is more useful when sending and receiving attachments than when dealing with simple messages. We will look how to leverage WSMessage in case of attachments in the future.

The simplest PHP Web Service Client

Wednesday, January 2, 2008

Yesterday I showed how to write a very simple Web service, form the article that I am currently writing.

Here is the simplest client, extracted form the same ongoing article.

  1. <?php

  2. $reqestPayloadString = <<<XML
  3. <knock>Knock, knock!!!</knock>
  4. XML;
  5.  
  6. $client = new WSClient(array("to" => "http://localhost/tutorial/first/service.php"));


  7. $response = $client->request($reqestPayloadString);

  8. echo "Service replied asking: '".$response->str."'\n";

  9. ?>

As in the case of the service, the client code is also very simple. The steps used in the client when consuming the service could be summarized as follows.

  1. Create the client instance with the service endpoint address (line 7)
  2. Send the request with the request message (line 9)
  3. Process the received response (line 11)

In this Web service client, when the WSClient instance is created, on line 7, we provide the endpoint address of the service we want to consume as the to option. The address used in this sample is the address of the service that we deployed in the previous section.

Form lines 3 to 5, we define the XML string to be sent as the request.

On line 9, the call to request() method of the WSClient instance, with the request XML string as a parameter, triggers the service invocation. Upon the call to request() method, Web service client forms the request message with the given XML string, sends the request to the service given in the to address and receives the response and stores the response in the WSMessage instance named response. You can access the incoming response as an XML string using the str member variable of the WSMessage instance.

Encrypting SOAP messages using PHP

In this blog I've described how to write a PHP script that uses WSO2 WSF/PHP to do secured web services...

The simplest PHP Web Service

Tuesday, January 1, 2008

I was writing an article on getting started with PHP Web services last few days, and I came up with this simple service to explain the minimal steps you need with WSO2 Web services framework to implement a service.

  1. <?php  
  2. function knock($message) {
  3.     $responsePayloadString = <<<XML
  4.             <knockResponse>Who is there?</knockResponse>  
  5. XML;
  6.     return $responsePayloadString;
  7. }

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

  9. $service->reply();

  10. ?>

This code could be broken into three main logical parts.

  1. Function implementing the service operation (lines 2 to 7)
  2. Creating service instance (line 8)
  3. Replying to client requests (line 9)
In this Web service, we have one operation named knock. As you can see on line 8, when the WSService instance is created, the set of operation could be given as an array. In this example, we have only one operation, hence there is only one element given in the operations array.

In this example, the function that implements the operation knock is function knock. This function takes an input parameter (line 2). This input parameter contains the request sent by the client, however in this example, we are not interested in the content of the request, hence we are not looking into the incoming message parameter. The logic implemented in the knock is very simple, we define the XML string to be returned as response (lines 3 to 5) and return the response XML string (line 6).

The call to reply() method of the WSService instance (line 9) triggers processing when there is a request form a client. It will locate the function implementing the invoked service operation, call the function with the incoming request content and prepare the response using the value returned by the function that was called. All these things happen transparent to the user.