我正在为驼鹿物体写一个模块.我想允许使用此对象的用户(或我自己……)根据需要随时添加一些字段.我无法先验地定义这些字段,因为我根本不知道它们是什么.
我目前只是添加了一个名为extra的hashref字段,它被设置为rw,因此用户可以简单地将东西放入该哈希:
# $obj is a ref to my Moose object $obj->extra()->{new_thingie}="abc123"; # adds some arbitrary stuff to the object say $obj->extra()->{new_thingie};
这很有效.但是……这是一种常见做法吗?还有其他(可能更优雅)的想法吗?
解决方法
我可能会通过本机特征来做到这一点:
has custom_fields => ( traits => [qw( Hash )],isa => 'HashRef',builder => '_build_custom_fields',handles => { custom_field => 'accessor',has_custom_field => 'exists',custom_fields => 'keys',has_custom_fields => 'count',delete_custom_field => 'delete',},); sub _build_custom_fields { {} }
在对象上,您可以使用以下内容:
my $val = $obj->custom_field('foo'); # get field value $obj->custom_field('foo',23); # set field to value $obj->has_custom_field('foo'); # does a specific field exist? $obj->has_custom_fields; # are there any fields? my @names = $obj->custom_fields; # what fields are there? my $value = $obj->delete_custom_field('foo'); # remove field value
像这样的东西的常见用例是向异常和消息类添加可选的内省数据.