使用Moose
和Bread::Board
,是否可以创建一个具有ArrayRef[SomeObject]
类型约束的属性的对象,并以如下方式注入该参数:
ArrayRef
约束,Bread::Board
和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
可以想象没有轮子,而我正在努力创造一种单轮轿车,但我认为你明白我的意思。 :-)这只是一个非常简单的例子。
答案 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 ];
},
)
};