in reply to Re: Re: Re: Passing self from class to class?
in thread Passing self from class to class?
Ah. I think I see what you're trying to do now. Let me re-state what I think it is, just in case I'm getting the wrong end of the stick.
I'm assuming that there is some reason that you have a separate initialise() method - perhaps you need to call it multiple times on the same object. If not, it might as well be called by new() at object creation time.
If the above outline is correct then some kind of state transition pattern would seem appropriate. There are several ways you could do this. Two that spring to mind are:
The latter method is very simple to implement. Indeed, if you change the parameter passed to 'area' to match the classname exactly (so it's "WidgetOne" rather than "widgetone" it becomes almost trivial.
sub run { my $self = shift; my $class = $self->{CGI}->param('area'); # We want to be careful that we're reblessing into a sensible cla +ss croak "$class not a subclass of OurParentPackage" unless UNIVERSAL::isa($class, 'OurParentPackage'); bless $self, $class; if ($self->{CGI}->param('act') eq 'add') { $self->add; } else { $self->default; } } package WidgetOne; use base qw(OurParentPackage); sub default { print "WidgetOne default\n" }; sub add { print "WidgetOne add\n" }; package WidgetTwo; use base qw(OurParentPackage); sub default { print "WidgetTwo default\n" }; sub add { print "WidgetTwo add\n" }; ... and so on for the other Widget* classes ...
The above solves the problem quite neatly, and you can add new Widget* subclasses without touching run().
I still don't know the purpose of the Widget classes, so this advice may be wrong, but I would also seriously consider refactoring the CGI object outside the Widget class hierarchy. It looks a little like an MVC pattern waiting to happen.
Hope this helps.
|
---|