perl鼠标在对象返回给用户之前设置的值

时间:2014-01-27 23:28:43

标签: perl perl-mouse

我正在尝试使用Mouse编写一个perl模块,并且在初始化对象之后,但在用户进行任何调用之前,我需要使用object2和object3中的两个值初始化object1用户被要求给予。我尝试使用Mouse的after功能来调用new之后的子程序:

package Test;
use strict;
use Mouse;

has 'object1'    => ( is => 'rw', isa => 'Any');
has 'object2'    => ( is => 'ro', isa => 'Str', required => 1); 
has 'object3'    => ( is => 'ro', isa => 'Str', required => 1); 

after 'new' => sub { 
    my ($self) = @_; 
    $self->object1(#do stuff with object2 and object3);
};

1;

但是,目前我收到此错误:

Invalid object instance: 'Test' at lib/Test.pm line 18.

有没有办法在用户获取返回给它们的对象引用之前用用户提供的值初始化值?

1 个答案:

答案 0 :(得分:2)

鼠标与Moose兼容。对象创建有以下几个阶段:

  1. 如果定义了参数,则通过BUILDARGS方法传递参数。这可以在Moose / Mouse触摸它们之前消除参数,例如提供默认参数或容纳除关键字约定之外的其他调用样式。
  2. 创建一个新实例,并填充字段(由has声明)。
  3. 现在设置对象并准备使用(从Mouse's / Moose的角度来看)。您可能对正确的设置有不同的想法,并且可以使用BUILD方法执行检查。在这一点上,您还可以执行无法用has声明表达的剩余初始化。
  4. 所以你的例子可能会成为:

    use strict;
    use warnings;
    
    package Your::Class;
    use Mouse;
    
    has 'object1' => ( is => 'rw', isa => 'Any');
    has 'object2' => ( is => 'ro', isa => 'Str', required => 1); 
    has 'object3' => ( is => 'ro', isa => 'Str', required => 1); 
    
    sub BUILD { 
        my ($self) = @_; 
        $self->object1($self->object2 . $self->object3);
    };
    
    package main;
    use Test::More;
    
    # Your::Class->new(object2 => "foo", object3 => "bar");
    my $instance = new_ok('Your::Class', [object2 => "foo", object3 => "bar"]);
    is($instance->object1, "foobar");
    
    done_testing;
    

    要了解有关Moose和Moose兼容对象系统中对象构造的更多信息,请阅读Moose::Manual::Construction