Automatic WSDL Generation in PHP 5

Downloads for the software described here are available on the downloads page.

About WSDL

WSDL (Web Services Description Language) is part of the XML Web Services technology platform. WSDL files describe to web service clients what services are available at a particular endpoint (server), and how the request and response messages should be (de)serialised. Find out more by reading the Web Services Description Language (WSDL) 1.1 W3C Note.

Typically, WSDL files are automatically generated from web service code using reflection, and are imported into clients at design-time. Visual Studio, for example, uses WSDL files to create proxy classes allowing the developer to call remote web services as simple method calls on a local object, making the process seamless (as if you were just calling a local method).

The two main platforms used for web services in the real world - J2EE and .NET - can both generate WSDL files easily from code because they are strongly typed languages. This is important because XML web services typically pass strongly typed data between client and server.

WSDL generation in PHP

PHP is a weakly typed language (meaning it is not necessary to declare a variable's content type when the variable itself is defined, and casts between eg. numbers and strings happen automatically depending on the context in which a variable is used), therefore reflection to generate WSDL files is impossible. This is a serious limitation for the applicability of PHP as a web services platform as it prevents PHP web services from having easy interoperability with clients written in other languages.

There have been several attempts to write WSDL auto-generation code for PHP. They typically work by having the developer provide additional data about the types of each argument and return value to each web service defined, for example in comments or arrays.

All of the published solutions are rather limited. Perhaps the best attempt I found is David Giffin's wsdl-writer-0.3, available at www.giffin.org. It operates by parsing comments immediately before a web service method to determine the types of its arguments. Here is a simple example:

class SimpleService {
    /**
     * Add method
     *
     * @param int $a First integer
     * @param int $b Second integer
     * @return int Result of addition
     */
    public function Add($a, $b)
    {
        return $a + $b;
    }
}


Some notes on syntax:

  • The comment parsing is very strict. You must not leave any empty lines between the closing */ and the method declaration.
  • Object properties must be declared using the exact syntax /** @var int Some integer value */ on the line immediately preceding the property declaration.
  • The types specified after @param and @return must be valid XSD types or complexTypes you have created yourself.

wsdl-writer does a very good job of generating WSDL for simple requests but has some major limitations as it stands. David unfortunately does not maintain wsdl-writer so I have decided to publish my modifications here.

WSDL Writer 0.3-katy.1

The following issues are addressed in this release:

Interoperability improvements:

  • PHP web services can now be imported into Visual Studio via their WSDL files (schema namespace fix)
  • When creating array types, the wsdl:arrayType attribute will now correctly use the xsd namespace for arrays of primitive types and tns (the target namespace) for arrays of complexTypes (previously tns was used for everything, which causes interoperability failures with .NET and Java)
  • Object complexType definitions with array properties will now be correctly serialised as eg. type="tns:ArrayOfstring" instead of type="tns:string[]" (this problem caused interoperability failures with .NET and Java)

Feature additions:

  • Binary attachments of type xsd:base64Binary are now supported
    • Specify "@param base64Binary $file" or "@return base64Binary" (case-sensitive) to trigger automatic encoding and decoding of binary arguments (such as images) at the client and server.
  • SOAP header support added
    • This is a significant enhancement which enables PHP web services to process eg. authentication or payment credentials supplied in headers, without having to modify every method of your web services to deal with authentication or other metadata that should preferably be supplied in headers.
    • To create a SOAP header processor in a PHP SOAP server, define methods in your web service class with the same names as the header elements you wish to process. The header methods will be called in document order followed by the body method, using a single instance of the class (the same instance will persist over each method call).
    • For automatic WSDL generation, specify that a method processes a SOAP header by including @internal soapheader before the method definition. To specify that a particular web service method requires certain SOAP headers, include @internal soaprequires FirstHeader SecondHeader .... (space-delimited list of header method names).
    • You can also create derived classes to facilitate encapsulation of SOAP header processing. This is desirable to avoid code repitition when you have several web service methods which use the same set of headers. To implement this, define a base class which processes your headers, and derive from it to create a web service class with your web service methods.
    • Limitations: The WSDL specification says that <soap:header> binding elements don't have to use the same <message> as those used by the <operation> being bound. My implementation only allows the same to be used. This should have no effect on your services in practice.
    • Limitations: .NET generates SOAP headers whose element names are the type names of their arguments. This means each header must include (and optionally return) precisely one argument; additionally the argument must be a complexType for the web service to import properly into Visual Studio. This also means that the PHP 5 method name which processes the header must be the same as the type name of its argument, eg. public function LoginObject($loginobject) where $loginobject is of type LoginObject. PHP 5 doesn't have the element naming, argument count or complexType restrictions, but in order to produce interoperable WSDL and eliminate the possibility of duplicate <part> names in a single <message> (where the arguments to a header and body method have the same name), my implementation co-erces part names representing headers to be the name of the type used as the argument, not the name of the argument itself. Therefore, if you use my implementation to generate WSDL, you must follow the .NET limitations, even if your client is PHP. Again, in practice, this should only be a minor inconvenience.
    • Access from .NET: In .NET languages such as C# and VB.NET, SOAP headers are available as read/write properties of the web service proxy class generated when your WSDL is imported into Visual Studio.
  • Objects and arrays are recursively scanned to an arbitrary depth for further objects and arrays, to correctly find and serialise all the types required to create a SOAP request into the <types> section of the WSDL file. This effectively means you can now pass and return types of arbitrary complexity among your web services - a very powerful enhancement.
    • Background: The original release of wsdl-writer-0.3 only scans the top level of types used (ie. the arguments and return parameters of each method). If any such argument or return parameter has properties which are themselves complexTypes or arrays of complexTypes (such as objects which have other objects or arrays of objects as public member variables), these are also needed in the <types> section to fully define the parent type.
    • Example: If you have a web service with returns an array of Foo, and Foo has properties of class types Bar and Baz, and Bar has a property of type array of string, the following types will be defined in the WSDL file: ArrayOfFoo, Foo, Bar, Baz and ArrayOfstring (the original release code would only include Foo and its type definition would be empty).

    Other bug fixes:

    • Command-line WSDL generation now works correctly
    • Multiple complexType class definitions in the same file which have some properties with the same name could cause the <types> section of the WSDL file to be generated incorrectly. This has been fixed.
    • Constructors and PHP magic methods will be excluded from the generated WSDL
      • SOAP servers using SOAP sessions may have a constructor in their web service classes to initialise new sessions to default values, so this exclusion is important
    • Strict Standards warnings in PHP 5 fixed

    Processing SOAP headers in a PHP SOAP server

    Here is an example of a web service class which processes headers and a body method:

     
    // To be supplied as a SOAP header element - remember that individual headers must
    // consist of exactly one complexType argument, so basic xsd types must be boxed in a class
    class WrappedString
    {
        /** @var string Data */
        public $data;
        
        public function __construct($s)
        {
            $this->data = $s;
        }
    }
    
    // Login credentials to be supplied as a SOAP header
    class LoginObject
    {
        /** @var int Login */
        public $login;
        /** @var int Password */
        public $password;
        
        public function __construct($l, $p)
        {
            $this->login = $l;
            $this->password = $p;
        }
    }
    
    // Arbitrary object returned by the test web service method
    // to prove that the header data was stored in the same class instance
    class TestObject
    {
        /** @var string Result string */
        public $result;
        /** @var int Demo session key */
        public $sessionkey;
        
        public function __construct($r, $k)
        {
            $this->result = $r;
            $this->sessionkey = $k;
        }
    }
    
    class MethodWithHeaders
    {
        public $sessionKey;
    
        /**
         * HeaderA SOAP header
         *
         * To process a SOAP header, create a function with the same name
    as the header's complexType.
         * Returned values will be sent back to the client as a SOAP response header.
         * This example returns the string in a response header, converted to uppercase.
         *
         * @param WrappedString $string Input string
         * @return WrappedString Capitalised string
         * @internal soapheader
         */
        public function WrappedString($string)
        {
            return new WrappedString(strtoupper($string->data));
        }
        
        /**
         * HeaderB SOAP header
         *
         * You don't have to return a value - you can store the details sent
         * in the header for later use.
         *
         * @param LoginObject $loginobject Username and password
         * @internal soapheader
         */
        public function LoginObject($loginobject)
        {
            $this->sessionKey = $loginobject->login * $loginobject->password;
        }
        
        /**
         * Some test web service
         *
         * Body function - shows that a single MethodWithHeaders object
         * instantiation is used for all the headers and the body method,
         * because $this->sessionKey hasn't been declared static.
         *
         * @param string $string Input string
         * @return TestObject Input string and demo session key based on
    header fields
         * @internal soaprequires WrappedString LoginObject
         */
        public function testfunction($string)
        {
            return new TestObject($string, $this->sessionKey);
        }
    }


    NOTE: Ironically the type hinting introduced into PHP 5.1 causes PHP SOAP servers to fail, so you should not use type hinting in your web service method or header prototypes.

    Supplying SOAP headers and accessing SOAP response headers in a PHP web service client

    The following code calls the server example above. Some items in [square brackets] require substitution as appropriate.

    // Create SOAP client using only WSDL
    $headersClient = new SoapClient("[Location of WSDL file]"); 
    
    // Create headers (use same element name and type name
    // for .NET interoperability - not required for PHP)
    $headerA = new SoapHeader('[Namespace URI of WrappedString]',
                     'WrappedString', new WrappedString('some test string')); 
    $headerB = new SoapHeader('[Namespace URI of LoginObject]',
                     'LoginObject', new LoginObject(14, 3)); 
    $headersClient->__setSoapHeaders(array($headerA, $headerB)); 
    
    // Standard call which passes input headers
    // but doesn't offer access to output headers
    $headersClient->testfunction("Echo me!")); 
    
    // Call which allows access to output headers
    // (input headers persist until changed)
    $headersClient->__soapCall('testfunction', array("Echo me again!"),
                               null, null, $outputHeaders); 
    print_r($outputHeaders);


    Note you need to include definitions of WrappedString or LoginObject in the client code.

    Final notes

    The changes to wsdl-writer and examples above have been tested against PHP 5.1.1 and Visual Studio .NET 2003 (.NET Framework 1.1). For general usage examples please refer to the examples supplied with the source code.

    I hope you find this code useful!

    Please send feedback using the contact page or use the comment form below.

  • louboutin

    Looking For discountchanel

    Looking For discountchanel replica
    Beautifulgucci handbags for sale
    油墨
    Balenciagafor sale
    Looking For discountchanel
    If you want to buylouis vuitton
    丝印器材
    Looking For discountchanel handbags
    Beautifulgucci for sale
    The store online sells theBalenciaga bags
    different kinds oflouis vuitton for cheap
    网版烤箱
    ghd straighteners for Cheap Wholesale
    If you want to buylouis vuitton bag
    different kinds oflouis vuitton handbag for cheap
    replica louis vuitton bag for for Cheap Wholesale
    ghd very cheap
    china Wholesale
    ghd hair straighteners for Cheap Wholesale
    移印器材
    replica louis vuitton bag for Cheap Wholesale

    We have the best chi tools of

    We have the best chi tools of the market, the original chi flat iron, chi ceramic, CHI Rocket Hair Dryer and chi straightener to get better styling results on your hair.

    Are u saying that she's

    Are u saying that she's needing some styling??
    Now way! she's fine like that!!

    Lara from budget hotels in Paris

    PHP functions to Javascript

    PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure...meilleur site de jeux de casino

    常德SEO

    陈水博客从事专业常德网站建设常德网站优化与网站建设培训,为常德企业提供常德seo,常德SEO优化,常德网站建设,有着多年的seo优化服务网站策划经验。

    Cheap Timberland Boots Sale

    Cheap Timberland Boots Sale - More than 1000 customers have got thecheap timberland boots ,
    Timberland Boots on sale
    . We hold the most competitive price, the first class service,buy now!

    pink ghd straighteners

    Ghd straighteners uk - buy the cheapest pink ghd straighteners in the UK.Use Compare ghd to find the biggest savings on ghd iv pink mk4,ghd flat Irons,ghd iv styelers and ghd Hair Straighteners pink.Cheap ghd uk hair straighteners found here.

    tall black uggs

    We supply UGG Boots UK ,black tall ugg boots,UGG Bailey Button,low price,offerWoolboots.com must be your best choice!

    chi hair straightener

    Save 60% off chi hair straighteners,we offer best Pink CHI Flat Iron ,Chi Camo Blue Ceramic Flat Iron in the market and 100% Quality Guarantee.

    cheap knight gold

    Gamers ought to know knight gold or knight online gold if they really like to play this game. All gamers want to buy knight gold or to buy Knight Online Premium to promote their character level easily, more Knight Noah and Knight Online Noah they own, more items they can buy in game. While we provide you cheap knight gold, surely you can get them at cheap prices. I think you must like Knight Premium if you are really a gamer.

    links of london

    Example: If you have a web service links london store with returns links london store an array of Foo, and Foo links london salelinks london sale has properties of class types Bar and Baz, and Bar has a property of type array of string, the following types will be defined in the WSDL file: Links London Necklaces ArrayOfFoo, Foo, Bar, Baz and ArrayOfstring (the original release code would only include Foo and its type definition would be empty).Support by UK shopping links of london earrings was intuitive and nowadays we have matured internationally with stores in 1990.links of londonThe party resulted from a clean exact for her wife,links london John Ayton, founded the jewelry mark,links of london sale links of london. Relations of London were founded in the UK, Hong Kong,links of london charms USA and Canada.links of london charms Links of London is one of the chief jewelry brands in the UK.

    Re

    If you try to find locality where you can buy term paper or buy research papers here is very adept place for you about essays writing, which furnish examples and gives an chance to learn how make review . But this site is more delightful, and more essential. So don't be lazy and write your own or buy essay about this topic. Thanks.

    Cheap ffxi gil

    how to buy Cheap ffxi gil

    Re

    I do think that it is executable to see this page, just because only here people will find the good enough theme close to this good post. Thus, the thesis service would take this for french dissertation making.

    cheap ugg adirondack boots,ugg coquette clearance sale

    YS0125L4 There are gains for all our losses. There are balms for all our pain; But when cheap ugg adirondack boots youth,the dream,departs It takes something ugg coquette clearance sale from our hearts, And it never comes discount ugg mayfaire boots again. We are stronger, and are better ugg elsey boots sale, Under manhood’s sterner reign;Still we feel that something wholesale ugg broome boots sweet Following youth, with flying feet, And will never come again. Something kids ugg boots sale beautiful is vanished, And we sigh for it in vain; We behold it http://www.uggboots4buy.com/ everywhere, On the earth, and in the air,But it never comes again!

    Re

    The quantities of humen all over the world heard about submit article and article submission site. It’s real to take it for such kind of good enough thought close to this good topic.

    basketball shoes

    Halfway through the year SPIN tipped their hand by offering the 20 Greatest Albums Of 2009 ... So Far. If you remember, the list wasn't in any specific order. Their 40 Best uggs sale Albums Of 2009 are, and it's interesting to see all the titles that popped up after the last one was published. As well as the

    albums that missed the cut after nike outlet
    they were spun a bit more: Peter Bjorn And John, Blk Jks, Regina Spektor, Glasvegas, Mavado, and Sa-Ra Creative Partners are nowhere to be found. The list -- one of oh so many

    lists -- is also refreshingly interesting in and of itself, a fine example of a publication nike outlet stepping outside of the hive mentality

    and coming up with something that feels personal. Even if I don't personally agree with a lot of it.

    basketball shoes

    My happiness is a small thing. Any one thing, as long as the willing, always simple. Easy to hurt others and themselves, and always away from the edge of obscure people. Desire to

    occupy more and more fragile. basketball shoesNo desire can only say that it is unsympathetic. A brief moment, long forever. Bird's

    wings in the air vibrations. It was a noisy and cold, and filled with the sound of fear. basketball shoes The flow of an uncertain

    fate. People's loneliness, and sometimes difficult language.Always need some warmth. Even a little self-righteous memorial. Sometimes the feelings of just one person thing. Has

    nothing to do with anyone. Love, or do not love, can only end their. Wound to give someone else a shame,cheap uggs its

    adherence to the illusion.

    eve online isk

    Every eve player want to get more and more eve isk, those who choose eve online isk make more progress than others. If you have not tried to buy eve isk and do not know where to buy eve online isk, you can come here: eve gold, click it!

    High quality fake rolex

    High quality fake rolex paypal of well known brands - Jacob & Co, TAG Heuer, Cartier, Panerai and much more. *If you want to buy replica watches paypal, you have come to the right place! We are leading supplier of all kinds of strongfake watches. The leading name in luxury watches, replica rolex paypal has been the pre-eminent symbol of performance and prestige for over a century. Replica Swiss Rolex men's and ladies' watches.

    Welcome to our website,and

    Welcome to our website,and you will enjoy the sunshine service. Let's abandon all the worry,and enjoy the happy shopping travel.All the replica watches paypal and replica watches are most in fashion boutique this year.rolex replica and rolex replica paypal and the replica rolex paypal show your chaming temperament. In addtin, the fake watches paypal and the other fake rolex paypal make you mold your unique glamour this winter.The swiss rolex replica have the high quality but low price. replica watch paypal and replica rolex have all the style and cheapest price replica rolex watches. Enjoying the fun of net purchase! replica rolex We will supply you the perfect service and after sale support system. Our honest will bring you absolute satisfaction.

    Post new comment

    The content of this field is kept private and will not be shown publicly.
    • Web page addresses and e-mail addresses turn into links automatically.
    • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <b> <i> <u> <pre> <sup> <sub> <h2> <h3> <h4>
    • Lines and paragraphs break automatically.

    More information about formatting options

    CAPTCHA
    This question is for testing whether you are a human visitor and to prevent automated spam submissions.
    Image CAPTCHA
    Copy the characters (respecting upper/lower case) from the image.

    Latest articles