Bread :: Board - 使用ArrayRef类型约束注入参数?

时间:2011-06-14 05:08:15

标签: perl moose bread-board

使用MooseBread::Board,是否可以创建一个具有ArrayRef[SomeObject]类型约束的属性的对象,并以如下方式注入该参数:

  • 维护ArrayRef约束,
  • 作为该ArrayRef成员的每个对象都具有Bread::Board
  • 所满足的所有依赖关系
  • 作为该ArrayRef成员的每个对象都是由Bread::Board创建的对象?

为了确保我清楚地解释自己,让我们考虑一个非常天真的例子。假设我们有一个Wheel类:

package Wheel;
use Moose;

has ['size', 'maker'] => (isa => 'Str', is => 'rw', required => 1);

让我们创建一个Vehicle类,其中每个实例都包含一堆轮子:

package Vehicle;
use Moose;

has 'wheels' => (
    is => 'rw',
    isa => 'ArrayRef[Wheel]',
    required => 1,
);

是否可以创建一个或多个Wheel实例,然后将包含这些实例的数组引用注入到我们的新Vehicle实例中?这显然不起作用:

my $c = container 'app' => as {
    container 'wheels' => as {
        service 'maker' => "Bob's Tires";
        service 'size' => "195R65/15";
        service 'carTires' => (
            class   => 'Wheel',
            dependencies => [ depends_on('maker'), depends_on('size') ],
        )
    };

    container 'vehicles' => as {
        service 'sedan' => (
            class   => 'Vehicle',
            dependencies => {
                # WON'T WORK
                wheels => depends_on('/wheels/carTires'),
            }
        )
    };
};
my $v = $c->resolve(service => 'vehicles/sedan');

有什么想法吗?是的,我知道我的Vehicle可以想象没有轮子,而我正在努力创造一种单轮轿车,但我认为你明白我的意思。 :-)这只是一个非常简单的例子。

1 个答案:

答案 0 :(得分:4)

您可以获得carTires服务以返回车轮的ArrayRef:

container 'wheels' => as {
    service 'carTires' => (
        block => sub {
            return [ map {Wheel->new} 1..4 ];
        },
    )
};

Vehicle构造函数将根据类型约束处理其余部分,因为您已将其定义为ArrayRef [Wheel]。

如果你这样做会死掉:

container 'wheels' => as {
    service 'carTires' => (
        block => sub {
            return [ map {Window->new} 1..4 ];
        },
    )
};