Hi list,
I am working on learning Moose, and I find it a little unclear in the
Moose::Manual::Attributes<http://search.cpan.org/~doy/Moose-2.0202/lib/Moose/Manual/Attributes.pod>manual
how accessors work. Here is an excerpt of the documentation:
"Each attribute has one or more accessor methods. An accessor lets you read
and write the value of that attribute for an object.
By default, the accessor method has the same name as the attribute. If you
declared your attribute as ro then your accessor will be read-only. If you
declared it read-write, you get a read-write accessor. Simple.
Given our Person example above, we now have a single first_name accessor
that can read or write a Person object's first_name attribute's value.
If you want, you can also explicitly specify the method names to be used for
reading and writing an attribute's value. This is particularly handy when
you'd like an attribute to be publicly readable, but only privately
settable. For example:
has 'weight' => (
is => 'ro',
writer => '_set_weight',
);
This might be useful if weight is calculated based on other methods. For
example, every time the eat method is called, we might adjust weight. This
lets us hide the implementation details of weight changes, but still provide
the weight value to users of the class."
1. The above gives me the impression that the accessor method
*replaces*(i.e., renames) the accessor methods. But as I understand
it, after paying
visiting the IRC channel, the accessor methods are also a way to
*bypass*the standard accessor methods. What is not clear is how
accessor write
methods store the value if I have
"foo => (is => 'rw', writer => 'set_foo')"
Perhaps the pattern is that if an accessor must store a value, it must do so
using a *different* attribute than what the accessor represents, sort of a
"private" attribute? So I would have:
_foo => (is => rw, isa => 'Str')
sub foo { ...$self->_foo(...) }
But then data validity checks may come too late, or will have to be done in
foo. It is a little confusing since normally sub foo {} stores the value in
$self->{foo}. Is there something I am missing, here? I have not really seen
this explained anywhere, but the manual is big and I can have missed it.
2. The above example in the manual shows a way to make an attribute
"publicly readable, but privately settable", but I don't see how the
"_set_weight" method can store the weight value? It does seem to say that
"_set_weight" above really updates other values in the object, and that the
value, when read, is derived from those other values. But if that is the
case, shouldn't there be a reader accessor for weight which derives the
value?
Or is it implied that _set_foo actually stores the value as described in
item 1) above?
Some light on this would be much appreciated.
Best Regards,
Gunnar