Moose:在BUILD方法中从文件加载对象

时间:2010-04-20 15:06:29

标签: perl build moose

我必须在BUILD方法中读取文件,并且我想使用MooseX :: Storage包的加载方法。
但是这个load方法创建了一个新对象,因此当我实例化对象时,这不是从文件中读取的对象。在下面的代码中,我创建了一个对象$ m1,状态为2,用于写入文件,我创建了$ m2,没有参数来读取文件,但是$ m2不包含正确的值。 包裹:

package mia;
use Moose;
use MooseX::Storage;

with Storage(format => 'JSON', io => 'File');

has 'nome'  => ( is     => 'rw', isa    => 'Str', default =>'',);
has 'stato' => ( is     => 'rw', isa    => 'Int', default =>1,);

sub BUILD{ 
my $self=shift;
    if ($self->stato==1){
      $self=mia->load("mia.dat");
    }
    if ($self->stato==2){
    $self->stato(0);
    $self->nome("prova");
    $self->store("mia.dat");    
 } 
sub stampa(){
my $self=shift;
print $self->nome." ".$self->stato;
}

主程序

use mia;
my $m;

$m1=mia->new(stato=>2); 
$m2=mia->new();
print "\nm1 \n";
$m1->stampa();
print "\nm2 \n";
$m2->stampa();

1 个答案:

答案 0 :(得分:5)

您的代码似乎就像BUILD是构造函数一样,它不是 - 它更像是一个构造后的钩子,您可以执行其他操作,例如从DB读取值。你应该改为:

  • mia->load的结果存储在属性中,并可选择使用委派的方法来访问它,或
  • mia->load 的结果用作对象,而不是构建单独的对象。

以下是第一种情况的示例,将MooseX :: Storage对象与控制它的对象分开:

package miaController;
use Moose;
use mia;

has 'nome'  => ( is     => 'rw', isa    => 'Str', default =>'',);
has 'stato' => ( is     => 'rw', isa    => 'Int', default =>1,);
has 'mia'   => ( is     => 'rw', isa    => 'mia', lazy => 1);

sub BUILD
{
    my $self = shift;
    if ($self->stato == 1)
    {
        $self->mia(mia->load("mia.dat"));
    }
    elsif ($self->stato == 2)
    {
        $self->stato(0);
        $self->nome("prova");
        $self->mia->store("mia.dat");
    }
}
sub stampa
{
    my $self = shift;
    print $self->nome." ".$self->stato;
}

package mia;
use Moose;
use MooseX::Storage;
with Storage(format => 'JSON', io => 'File');

package main:
use miaController;

my $m1=miaController->new(stato=>2);
my $m2=miaController->new();
print "\nm1 \n";
$m1->stampa();
print "\nm2 \n";
$m2->stampa();