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:
|
|---|
| 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 |