perl - Moose structured types -
i'd create structured type in moose can used type moose attribute. example, i'd able create name
attribute has own value
, error
attributes.
i therefore know best way of achieving this. have created working example defining simple moose class represent generic field
object. has value
, error
attributes. have created moose class person
object. has id
, name
attributes, both of of type field
:
define generic field object:
package myapp::type::field; use moose; use namespace::autoclean; has 'value' => ( => 'rw' ); has 'error' => ( => 'rw', isa => 'str' ); __package__->meta->make_immutable; 1;
define person object uses field object:
package myapp::person; use moose; use namespace::autoclean; use myapp::type::field; has 'id' => ( => 'rw', isa => 'myapp::type::field' ); has 'name' => ( => 'rw', isa => 'myapp::type::field' ); __package__->meta->make_immutable; 1;
do person object:
package myapp::test; use moose; use namespace::autoclean; use myapp::person; $person = myapp::person->new(); # works. $person->id( myapp::type::field->new() ); $person->id->value( 1 ); $person->id->error( 'not found' ); # fails name object has not yet been defined. $person->name->value( 'dave' ); # can't call method "value" on undefined value @ ... __package__->meta->make_immutable; 1;
this works, in myapp::test
able directly access value
, error
attributes of person's name
, id
without first having instantiate new myapp::type::field
object each of person's attributes.
or, put way, i'd prefer if user of person
class did not have this: $person->id( myapp::type::field->new() );
before being able use id
attribute.
is there nice clean way can achieve this?
couldn’t supply default
properties?
has 'id' => ( => 'rw', isa => 'myapp::type::field', default => sub { myapp::type::field->new } );
…or equivalent in build
.
Comments
Post a Comment