加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 如何在Moose强制中访问我的对象的属性?

发布时间:2020-12-16 06:16:33 所属栏目:大数据 来源:网络整理
导读:我想将一个Str强制转换为我的Moose类中的属性的DBIx :: Class :: Row对象.为此,我需要在DBIC模式上执行查找以查找行.如果查找失败,我想将错误推送到ArrayRef属性. 我目前将模式作为属性传递给我的类. 有了强制,我似乎无法访问该对象,因此我无法推送错误的arr
我想将一个Str强制转换为我的Moose类中的属性的DBIx :: Class :: Row对象.为此,我需要在DBIC模式上执行查找以查找行.如果查找失败,我想将错误推送到ArrayRef属性.

我目前将模式作为属性传递给我的类.

有了强制,我似乎无法访问该对象,因此我无法推送错误的arrayref属性或使用模式对象来执行查找.

我尝试的另一种方法是使用’around’来查找并设置属性,但是当通过构造函数传递属性值时,这当然不会被调用.

这是可能的,还是有人有替代实现来做我想要实现的目标?

解决方法

当传递给具有属性初始值设定项的构造函数时,您可以捕获并改变存储的值. (但是,它仅在构造函数中设置属性时运行,而不是在任何其他时间运行.)初始值设定项的文档可在 Class::MOP::Attribute中找到.

由于这只捕获通过构造函数设置属性的情况,因此您仍然需要捕获设置该属性的其他情况.这可以通过你所说的方法修饰符来完成,但你可以将这两个方法组合成一个方法,包裹在自动生成的访问器中:

has my_attr => (
    is => 'rw',isa => 'DBIx::Class::Row',initializer => 'my_attr',);

# my_attr is the autogenerated accessor - we method-modify it to mutate the
# value being set,and catch cases where it is called as an initializer.

# called for reads,writes,and on initialization at construction time
around 'my_attr' => sub {
    my $orig = shift;
    my $self = shift;
    # value is not defined if being called as a reader
    # setter and attr are only defined if being called as an initializer
    my ($value,$setter,$attr) = @_;

    # the reader behaves normally
    return $self->$orig if not @_;

    # convert the string to the row object
    my $row = $self->convert_str_to_row_obj($value);

    # if called as an initializer,set the value and we're done
    return $setter->($row) if $setter;

    # otherwise,call the real writer with the new value
    $self->$orig($row);
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读