Bread :: Board中的默认值/可替换值

时间:2012-03-29 00:27:21

标签: perl inversion-of-control moose bread-board

我发现自己在很多测试中实例化了相同的对象,所以我试图用Bread::Board替换这个常量设置。大多数时候,我希望依赖项具有相同的配置。但偶尔我可能想要使用非默认参数创建实例。我还希望能够在创建容器实例后更改此设置。例如我通常想要

my $c = Test::Container->new;

my $bar = $c->resolve( service => 'bar' ); # where bar depends on foo

但有时我真正需要的是

my $bar = $c->resolve( service => 'bar', {
              services => {
                foo => { init => 'arg' }
              }
          }

以便在创建bar实例时以不同方式初始化service foo。

1 个答案:

答案 0 :(得分:0)

这是Jesse Luehrs (Doy)在#moose上提供给我的,看来它会做我想做的事。

#!/usr/bin/env perl
use v5.14;
use strict;
use warnings;

package Container {
use Moose;
use Bread::Board;

extends 'Bread::Board::Container';

has '+name' => (default => 'Container');

sub BUILD {
    my $self = shift;
    container $self => as {
        service foo => (
            block => sub {
                my $s = shift;
                $s->param('foo_val');
            },
            parameters => {
                foo_val => { isa => 'Str' },
            },
        );
        service bar => (
            block => sub {
                my $s = shift;
                $s->param('foo')->inflate(foo_val => $s->param('foo_val')) . 'BAR';
            },
            dependencies => ['foo'],
            parameters => {
                foo_val => { isa => 'Str', default => 'FOO' },
            },
        );
    };
}
}

my $c = Container->new;
warn $c->resolve(service => 'bar');
warn $c->resolve(service => 'bar', parameters => { foo_val => 'baz' });