在 Moose 中创建类属性的最佳方法是什么?
我需要 Moose 中的类属性。 现在我要说的是:
#!/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";
}
I need a class attribute in Moose. Right now I am saying:
#!/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";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了 MooseX::ClassAttribute,但它看起来很难看。 这是最干净的方式吗?
I found MooseX::ClassAttribute, but it looks ugly. Is this the cleanest way?
老实说,我认为没有必要为类属性带来那么多麻烦。 对于只读类属性,我只使用返回常量的 sub。 对于读写属性,包中的一个简单的状态变量通常可以解决问题(我还没有遇到任何需要更复杂的东西的场景。)
如果您需要 5.10 之前的版本,可以使用带有词法的私有块兼容性。
Honestly, I don't think it's necessary to all that trouble for class attributes. For read-only class attributes, I just use a sub that returns a constant. For read-write attributes, a simple state variable in the package usually does the trick (I haven't yet run into any scenarios where I needed something more complicated.)
A private block with a lexical can be used if you need pre-5.10 compatibility.