What is the most efficient way to override an attribute in lots of my Moose based sub classes? - perl

I am using HTML::FormHandler. To use it one is supposed to subclass from it and then you can override some attributes such as field_name_space or attribute_name_space.
However, I now have lots of forms all extending HTML::FormHandler or its DBIC based variant HTML::FormHandler::Model::DBIC and therefore have these overidden attributes repeated many times.
I tried to put them in a role but get an error that +attr notation is not supported in Roles. Fair enough.
What is the best way of eliminating this repetition? I thought perhaps subclassing but then I would have to do it twice for HTML::FormHandler and HTML::FormHandler::Model::DBIC, plus I believe general thought was that subclassing is generally better achieved with Roles instead.
Update: I thought it would be a good idea to give an example. This is what I am currently doing - and it involves code repetition. As you can see one form uses a different parent class so I cannot create one parent class to put the attribute overrides in. I would have to create two - and that also adds redundancy.
package MyApp::Form::Foo;
# this form does not interface with DBIC
extends 'HTML::Formhandler';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
...
package MyApp::Form::Bar;
# this form uses a DBIC object
extends 'HTML::Formhandler::Model::DBIC';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
...
package MyApp::Form::Baz;
# this form also uses a DBIC object
extends 'HTML::Formhandler::Model::DBIC';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
...

First of all, roles are composed into a class, they have nothing to do with subclassing. A subclass is a full class that extends a parent (or more than one, but in my experience multiple inheritance should be avoided if it can be). A role is a piece of behaviour, or a parial interface that can be applied to a class. The role then directly modifies the class. There's no new class created in general.
So inheritance and role composition are really two different things and two different kinds of design. Thus you can't simply exchange one for the other. Both have different design-implications.
My strategy with HTML::FormHandler has been to make a real subclass for each form that I require, and put the different behaviours of the form that I wanted to re-use into roles.
I'd think this question (how to implement the extensions you need in a clean and sane way) can't really be answered without knowing the actual design you're aiming for.
Update: I see what you mean and that's a tricky case. HTML::FormHandler is primarily targetted at extension by inheritance. So I think the best strategy would indeed be to have two subclasses, one for HTML::FormHandler and one for HTML::FormHandler::Model::DBIC. It seems teadious at first, but you might want to have different settings for them in the long run anyway. To avoid repeating the actual configuration (the default values) I'd try the following (this example is plain HFH, without DBIC):
package MyApp::Form;
use Moose;
use namespace::autoclean;
extends 'HTML::FormHandler';
with 'MyApp::Form::DefaultSettings';
# only using two fields as example
for my $field (qw( html_prefix field_traits )) {
has "+$field", default => sub {
my $self = shift;
my $init = "_get_default_$field";
my $method = $self->can($init)
or die sprintf q{Class %s does not implement %s method}, ref($self), $init;
return $self->$method;
};
}
1;
Note that you'd need to make an attribute lazy if it requires the values of another attribute for its computation. The above base class would look for hooks to find the initialized values. You'd have to do this in both classes, but you could put the default subroutine generation into a function you import from a library. Since the above doesn't require direct manipulation of the attribute anymore to change the default values, you can put that stuff in a role I called MyApp::Form::DefaultSettings above:
package MyApp::Form::DefaultSettings;
use Moose::Role;
use namespace::autoclean;
sub _build_html_prefix { 1 }
sub _build_field_traits { ['MyApp::Form::Trait::Field'] }
1;
This method will allow your roles to influence the default value construction. For example, you could have a role based on the one above that modifies the value with around.
There is also a very simple, but in my opinion kind-of ugly way: You could have a role provide a BUILD method that changes the values. This seems pretty straight-forward and easy at first, but it's trading extendability/flexibility with simplicity. It works simple, but also only works for very simple cases. Since the amount of forms in web applications is usually rather high, and the needs can be quite diverse, I'd recommend going with the more flexible solution.

The code for HTML::FormHandler::Model::DBIC is actually in a Moose trait in order to help with this situation. You can inherit from your base class, and in your forms that use the DBIC model, you can do
with 'HTML::FormHandler::TraitFor::Model::DBIC';

Would this method, using multiple inheritance (I know I know, ugh), where you put your common default overrides in one class, and then your customized code in others?
package MyApp::Form;
use Moose;
extends 'HTML::Formhandler';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
package MyApp::Form::Model::DBIC;
use Moose;
extends 'MyApp::Form', 'HTML::Formhandler::Model::DBIC';
# ... your DBIC-specific code
Now you can descend from MyApp::Form or MyApp::Form::Model::DBIC as needed.

Related

Moops lexical_has and default values

I am trying to understand how lexical_has attributes work in Moops. This feature comes from Lexical::Accessor and, as I understand it, the lexical_has function is able to generate a CODE reference to any attribute a class might "lexically have" by using a scalar reference (which is kept in accessor =>). The CODE reference can then be used to access the class attribute in a way that "enforces" scope (because they are "inside out"??). But this is just my surmise and wild guesses so I would appreciate a better explanation. I also want to know why this approach doesn't seem to work in the following example:
Working from the example that is part of the Moops introduction I'm creating a class Car:
use Moops;
class Car {
lexical_has max_speed => (
is => 'rw',
isa => Int,
default => 90,
accessor => \(my $max_speed),
lazy => 1,
);
has fuel => (
is => 'rw',
isa => Int,
);
has speed => (
is => 'rw',
isa => Int,
trigger => method ($new, $old?) {
confess "Cannot travel at a speed of $new; too fast"
if $new > $self->$max_speed;
},
);
method get_top_speed() {
return $self->$max_speed;
}
}
Then I instantiate the object and try to use its methods to access its attributes:
my $solarcharged = Car->new ;
# This correctly won't compile due to $max_speed scoping:
# say $solarcharged->$max_speed;
# This shows expected error "too fast"
$solarcharged->speed(140);
# This prints nothing - wrong behavior?
say $solarcharged->get_top_speed();
The last line which uses the custom accessor baffles me: nothing happens. Am I missing an attribute or setting for the class (marking it eager or lazy => 0 doesn't work)? Do I need a BUILD function? Is there an initialization step I'm missing?
N.B. If I add a setter method to the class that looks like this:
method set_top_speed (Int $num) {
$self->$max_speed($num);
}
and then call it in my final series of statements:
# shows expected error "too fast"
$solarcharged->speed(140);
$solarcharged->set_top_speed(100);
# prints 100
say $solarcharged->get_top_speed();
the get_top_speed() method starts to return properly. Is this expected? If so, how does the default from the class settings work?
I've reported this as a bug here: https://rt.cpan.org/Public/Bug/Display.html?id=101024.
Since One can easily work around this by using "perl convention" (i.e. not using lexical_has and prefixing private attributes with "_") and this question arose from a bug, I don't expect a fix or a patch as an answer. For the bounty - I would appreciate an explanation of how Lexical::Accessor is supposed to work; how it "enforces" private internal scope on accessors; and maybe some CS theory on why that is a good thing.
According to the ticket filed by the OP, this bug was fixed in Lexical-Accessor 0.009.

How to implement a class constant that is different for each subclass?

In my class hierarchy, I need a common attribute where each subclass needs to provide a different value that is constant for all objects of that class. (This attribute serves as a key to an existing hierarchy that I'm mirroring -- not the best OO design, but I need to preserve this link.)
One way to implement this is with attributes, like this:
package TypeBase;
use Moose::Role;
has type => (
is => 'ro',
isa => enum([qw(A B)]),
builder => '_type',
init_arg => nil,
required => 1,
);
1;
#####
package TypeA;
use Moose;
with 'TypeBase';
sub _type { 'A' };
1;
#####
package TypeB;
use Moose;
with 'TypeBase';
sub _type { 'B' };
1;
Is there a better way to do this? I could just have requires 'type' in the base class, which each concrete class would have to provide, except that this loses me the type constraint that I had with the attribute route.
My solution is equivalent to yours in terms of the external interface. The main difference is the use of constant to better reflect what you are doing. (Note that TYPE can still be called like a method.) Because if is using requires it should also give you a compile-time rather than runtime error if you haven't implemented TYPE in one of your classes.
package TypeBase;
use Moose::Role;
requires 'TYPE';
package TypeA;
use Moose;
with 'TypeBase';
use constant TYPE => 'A';
package TypeB;
use Moose;
with 'TypeBase';
use constant TYPE => 'B';

Moose creating accessors

given a list of accessors is the following possible? If it is possible how would i create builder method for each, i assumed lazy_build attribute would be doing that? please help
my #accessors= qw/type duration process/; # used 3 as example but the list is about 50
foreach my $accessors (#accessors) {
has $accessors => (
is => 'rw',
isa => 'Str',
lazy_build => 1,
);
}
Yes, it's possible. It is both documented to work and trivial to test.
As documented, lazy_build does not create builders; it specifies that an attribute should be lazily initialized and that it should call a builder named _build_${attr_name}. You have to supply your own builder methods called _build_type etc.
If your attributes all take the same builder (unlikely, but maybe they do), don't say lazy_build. Instead, say lazy => 1, builder => '_build_stuff' and implement _build_stuff to work for each case. But like I said, that's unlikely; the fact that you can easily use it in a loop is in fact one of lazy_build's advantages.

Perl Moose Hash traits

I have a parameter object in Moose which has attributes of file wildcards to glob
So I had a method to do this
sub getInputFileParams{
my ($self) = #_;
#the only parameters passed in are in fact the input files
return keys(%{$self->{extraParams}});
}
but then I though why not iterate the attributes as a hash?
has 'extraParams' => (
is => 'ro',
isa => 'JobParameters::Base',
default => sub { {} },
traits => ['Hash'],
handles => {
keys_extraParams => 'keys',
},
);
However that chokes as its not a hash reference. have I missed something or is using the object as a hash bad
Yes, using objects as plain hashes is bad.
You're accessing their internal state directly, which bypasses any interface that they may present and makes your class closely coupled to the internal representation of the JobParameters::Base class.
If you need to be able to get the contents of a JobParameters::Base object as a hash, then add a to_hash method to JobParameters::Base, and delegate to that method in your attribute...
This means that if later you add caching (for example!) to JobParameters::Base, and use a __cache key to store internal data, you can safely make this change by also changing the to_hash method to remove the internal data from the hash it returns.
It is fine to store an attribute as just a hash, but if you're storing a blessed hash, then don't reach into it's guts..
You've got all tools in place in your Moose class definition, you just aren't using them - try this:
return $self->keys_extraParams

Moose - Why does Accessor defined in sub role does not satisfy parent role requires

I am defining an API using roles and also defining the implementation using roles. I combine multiple implementation roles into a class just before creating objects. I am running into an issue where accessor methods are not being recognized while normal methods are. Please see code below and errors received while running it. I wonder if this is an intended behavior or a bug?
Code:
use MooseX::Declare;
role api { requires qw(mymethod myattribute); }
role impl with api {
has myattribute => (is => 'ro', default => 'zz');
method mymethod { ...; }
}
class cl with impl {}
my $obj = cl->new;
Error:
'impl' requires the method 'myattribute' to be implemented by 'cl' at D:/lab/sbp
/perl/site/lib/Moose/Meta/Role/Application/ToClass.pm line 127
So the issue here (and I think it's being masked by MooseX::Declare) is a known issue where Role composition may happen before the methods are generated by the attribute. If you change your code to move the role composition to after the attribute declaration:
role impl {
has myattribute => (is => 'ro', default => 'zz');
with qw(impl);
method mymethod { ...; }
}
and the error goes away. I thought MooseX::Declare protected you against this by moving role composition to the end of the role/class declaration but it appears that isn't the case in this instance. Perhaps someone who uses MooseX::Declare more can illuminate better what's going on there.