我正在为驼鹿物体写一个模块.我想允许使用此对象的用户(或我自己……)根据需要随时添加一些字段.我无法先验地定义这些字段,因为我根本不知道它们是什么.
我目前只是添加了一个名为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
像这样的东西的常见用例是向异常和消息类添加可选的内省数据.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。