in reply to auto generating wrapper classes for complex types defined in WSDL

Why do you want classes instead of data structures? If all you want is an object with get/set methods, I don't see how that's all that different from a structure with getable/setable key-value pairs. An object would prevent the user from accidentally using some wrong name (i.e., it prevents typos), but otherwise you're just giving them a structure with more access overhead.

That said, generating a simple object from a hash is not that hard.

use strict; use warnings; sub hash2obj { my $hash_ref = shift; my $package = shift; bless $hash_ref => $package; foreach my $key ( keys %{$hash_ref} ) { no strict 'refs'; *{$package.'::get_'.$key} = sub { $_[0]->{$key} }; *{$package.'::set_'.$key} = sub { $_[0]->{$key} = $_[1] }; } return $hash_ref; } use Test::More 'tests' => 8; my $t1 = { a => 1, b => 2 }; hash2obj( $t1, 'Test::One' ); isa_ok( $t1, 'Test::One' ); can_ok( $t1, 'set_a' ); can_ok( $t1, 'set_b' ); can_ok( $t1, 'get_a' ); can_ok( $t1, 'get_b' ); is( $t1->{a}, $t1->get_a(), 'get_a same as $t1->{a}' ); $t1->set_a(3); is( $t1->get_a(), 3, 'a is 3 after set' ); is( $t1->{a}, $t1->get_a(), 'get_a same as $t1->{a} after set' );

This has some caveats:

  • Comment on Re: auto generating wrapper classes for complex types defined in WSDL
  • Download Code

Replies are listed 'Best First'.
Re^2: auto generating wrapper classes for complex types defined in WSDL
by cwilliams (Novice) on Oct 11, 2007 at 22:33 UTC
    Yes, I could create the classes by hand, and that is what I may end up doing. But I would want more than just get/set methods. I'd love to have type checking and proper interpretation of the data that came from the server.

    I'd rather have this autogenerated. All the data is in the WSDL, so I shouldn't have to redo it all.

    Let me explain one problem I've seen a few times which is one of the reasons that pushed over over the edge from being happy with hashes to wanting classes.

    For this example, lets say I'm talking to a bug tracking system and the call returns a bug. Each bug can have 0 or more comments. If there is no comments the XML that comes back looking like

    <Commments></Comments>
    
    In which case SOAP::Lite decodes this as a string. If I get one:
    <Commments><Comment>blah</Comment></Comments>
    
    Which means Comments points to a hash {Comment => 'blah' }. If I have multiple comments:
    <Commments><Comment>blah</Comment><Comment>foo</Comment></Comments>
    
    Then I get Comments pointing to an array of hashes.

    This is annoying for end users to deal with. The WSDL defines the Comments type as an array of Comment types, and the user expects it to be an array even if there is only one or zero elements.

    And yes, I could write my classes to deal with this, but I'd rather not have too. If I was doing a lot of these, I'd definitely want an automated tool.