water has asked for the wisdom of the Perl Monks concerning the following question:

Hi --

I want to subclass Class::MakeMethods (to, say, MyMakeMethods) such that optional and required fields can be specified.

My goal: to have a MyMakeMethods such that I can then create a new class Foo (subclassing MyMakeMethods) with (say) scalar parameters x,y,z, where x and y must be defined on creation (and, say, z is optional). If x and y not defined, then the call to new dies.

I am having a hard time seeing how to wrap C:MakeMethods this way and would welcome suggestions.

Thanks

water

Replies are listed 'Best First'.
Re: subclassing MakeMethods
by simonm (Vicar) on Dec 07, 2004 at 18:19 UTC
    Hello, and thanks for your interest in Class::MakeMethods.

    Subclassing Class::MakeMethods to add new types of methods is described in the "Extending" section of the documentation.

    package MyMakeMethods; use Class::MakeMethods '-isasubclass'; sub new { map { my $name = $_->{name}; my @required = split ' ', $_->{required}; $name => sub { my ( $class, %params ) = @_; die unless exists $params{$_} foreach ( @required ); bless \%params, $class; } } (shift)->_get_declarations( @_ ); } sub get_set { 'Standard::Hash:scalar' } 1;

    However, you don't need to subclass again to use those new method types; just use Class::MakeMethods's regular calling interface:

    package MyFoo; use MyMakeMethods ( new => { name => 'new', required => 'x y' }, get_set => 'x y z', ); 1;

    That's untested, but it should get you started. Usage might look like the following:

    package main; use MyFoo; my $foo = MyFoo->new( x => 'Xerces', y => 'Yes' );
      <dumbquestion> Thanks!! Was this (the untested required param in 'new') mentioned in the docs anywhere? I could not / still can't find it. </dumbquestion>

      UPDATED -- I didn't understand simonm's code, so my question above about being in the docs makes no sense. Now I see what simonm's suggesting: this isn't in the docs, he did create MyMakeMethods. Got it. water