Moose:当属性值改变时,计算的缓存结果会过期吗? [英] Moose: Expiring cached results of calculations when attribute values change?

查看:34
本文介绍了Moose:当属性值改变时,计算的缓存结果会过期吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的类中,我们有一个模式,我们创建一个属性来表示计算值.出于显而易见的原因,我们希望缓存计算值然后在底层值之一更改时使缓存无效.

In our classes we have a pattern where we create an attribute to represent a calculated value. For obvious reasons we want to cache the calculated value and then invalidate the cache when one of the underlying values change.

所以我们目前有这个:

package FooBar;
use Moose;

has 'foo' => (
        accessor => {
            'foo' => sub {
                my $self = shift;
                if (@_ > 0) {
                    # writer
                    $self->{foo} = $_[0];

      # reset fields that are dependant on me
      $self->{bar} = undef;
                }
                # reader part;
                return $self->{foo};
            }
        }
    );

has 'bar' => (
        accessor => {
            'bar' => sub {
                my $self = shift;
                if (@_ > 0) {
                    # writer
                    $self->{bar} = $_[0];
                }
                # reader part;
                $self->{bar} = calculate_bar($self->foo, $self->baz) 
                        if (not defined($self->{bar}));
                return $self->{bar};
            }
        }
    );

sub calculate_bar { ... }

这种长手方法在计算值时变得非常乏味且容易出错取决于其他计算值.

This long hand method is getting very tedious and error prone when calculated values depend on other calculated values.

'bar' 是否有更智能/更简单的方法来监控它所依赖的属性vs 'foo' 知道谁依赖它?另外我怎样才能避免通过哈希设置栏会员访问?

Is there a smarter/simpler way for 'bar' to monitor the attributes it depends on vs having 'foo' know who is dependent on it? Also how can I avoid setting bar via hash member access?

推荐答案

我认为您很可能通过使用带有惰性的 Attributes 隐式记忆来增加自己的难度,而您可以只使记忆显式你的整个程序更透明

I think it is quite possible that you're making this harder on yourself by using an Attributes implicit memoization with lazy, when you could just make the memoization explicit making your whole program more transparent

has [qw/foo bar baz/] => ( isa => 'Value', is => 'rw' );

use Memoize;
memoize('_memoize_this');

sub old_lazy_attr {
    my $self = shift;
    _memoize_this( $self->attr1, $self->attr2, $self->attr3 );
}

sub _memoize_this {
    my @args = @_;
    # complex stuff
    return $result
}

有关内部缓存的信息和控制,请参阅 cpan 的 Memoize,还请记住一个 Memoized函数不能依赖于对象的状态.所以参数必须显式传入.

See cpan's Memoize for information and control of the internal cache, also remember that a Memoized function can not be dependent on the state of the object. So the arguments must be passed in explicitly.

这篇关于Moose:当属性值改变时,计算的缓存结果会过期吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆