在Moose中创建类属性的最佳方法是什么?

时间:2009-06-29 01:31:44

标签: perl moose

我需要Moose中的class属性。现在我说:

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use MooseX::Declare;

class User {
    has id      => (isa => "Str", is => 'ro', builder => '_get_id');
    has name    => (isa => "Str", is => 'ro');
    has balance => (isa => "Num", is => 'rw', default => 0);

    #FIXME: this should use a database  
    method _get_id {
        state $id = 0; #I would like this to be a class attribute
        return $id++;
    }
}

my @users;
for my $name (qw/alice bob charlie/) {
    push @users, User->new(name => $name);
};

for my $user (@users) {
    print $user->name, " has an id of ", $user->id, "\n";
}

2 个答案:

答案 0 :(得分:8)

我找到了MooseX :: ClassAttribute,但它看起来很难看。这是最干净的方式吗?

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use MooseX::Declare;

class User {
    use MooseX::ClassAttribute;

    class_has id_pool => (isa => "Int", is => 'rw', default => 0);

    has id      => (isa => "Str", is => 'ro', builder => '_get_id');
    has name    => (isa => "Str", is => 'ro');
    has balance => (isa => "Num", is => 'rw', default => 0);

    #FIXME: this should use a database  
    method _get_id {
        return __PACKAGE__->id_pool(__PACKAGE__->id_pool+1);
    }
}

my @users;
for my $name (qw/alice bob charlie/) {
    push @users, User->new(name => $name);
};

for my $user (@users) {
    print $user->name, " has an id of ", $user->id, "\n";
}

答案 1 :(得分:2)

老实说,我认为没有必要为类属性带来麻烦。对于只读类属性,我只使用返回常量的子。对于读写属性,包中的一个简单状态变量通常可以解决问题(我还没有遇到任何需要更复杂的事情的场景。)

state $count = 0;
method _get_id { 
    return ++$count;
}

如果您需要5.10之前的兼容性,可以使用带词法的私有块。