使用Moose,是否可以創建一個可以一次構建多個屬性的構建器?如何使用Moose中的單個構建器構建多個屬性?
我有一個項目,其中的對象有幾個'集'的字段 - 如果該集的任何成員被請求,我想繼續並填充它們。我的假設是,如果我需要名稱,我還需要生日,並且由於它們在同一個表中,所以在一個查詢中獲得這兩個名稱會更快。
我不確定我的問題是否足夠清晰,但希望某些示例代碼能夠清楚說明。
我有什麼:
Package WidgetPerson;
use Moose;
has id => (is => 'ro', isa => 'Int');
has name => (is => 'ro', lazy => 1, builder => '_build_name');
has birthdate => (is => 'ro', lazy => 1, builder => '_build_birthdate');
has address => (is => 'ro', lazy => 1, builder => '_build_address');
sub _build_name {
my $self = shift;
my ($name) = $dbh->selectrow_array("SELECT name FROM people WHERE id = ?", {}, $self->id);
return $name;
}
sub _build_birthdate {
my $self = shift;
my ($date) = $dbh->selectrow_array("SELECT birthdate FROM people WHERE id = ?", {}, $self->id);
return $date;
}
sub _build_address {
my $self = shift;
my ($date) = $dbh->selectrow_array("SELECT address FROM addresses WHERE person_id = ?", {}, $self->id);
return $date;
}
但我想要的是:
has name => (is => 'ro', isa => 'Str', lazy => 1, builder => '_build_stuff');
has birthdate => (is => 'ro', isa => 'Date', lazy => 1, builder => '_build_stuff');
has address => (is => 'ro', isa => 'Address', lazy => 1, builder => '_build_address');
sub _build_stuff {
my $self = shift;
my ($name, $date) = $dbh->selectrow_array("SELECT name, birthdate FROM people WHERE id = ?", {}, $self->id);
$self->name($name);
$self->birthdate($date);
}
sub _build_address {
#same as before
}
好的模式,但如果有很多屬性,有沒有辦法避免重複:build =>'_build_attribute1'... sub _build_attribute1 {my $ self = shift;返回$ self-> raw_row - > {attribute1}; } 一遍又一遍地?也許有一種方法讓_build_attribute識別調用它的屬性? – yahermann 2017-03-18 05:00:45
@yahermann,我認爲這個問題已經到了。如果你可以做你的建議,這個問題就不存在了。 – UncleCarl 2018-03-06 23:37:42