415
|
1 package IMPL::Config::ServiceDescriptor;
|
|
2 use strict;
|
|
3
|
|
4 use IMPL::lang qw(:base);
|
|
5 use IMPL::Exception();
|
|
6 use IMPL::declare {
|
|
7 require => {
|
416
|
8 Bag => 'IMPL::Config::Bag',
|
|
9 ActivationException => 'IMPL::Config::ActivationException'
|
415
|
10 },
|
|
11 base => [
|
|
12 'IMPL::Object' => undef,
|
|
13 'IMPL::Config::Descriptor' => undef
|
|
14 ],
|
|
15 props => [
|
|
16 type => 'ro',
|
|
17 activation => 'ro',
|
|
18 args => 'ro',
|
|
19 services => 'ro',
|
|
20 _name => 'rw',
|
|
21 _loaded => 'rw'
|
|
22 ]
|
|
23 };
|
|
24
|
|
25 sub CTOR {
|
|
26 my ( $this, %opts ) = @_;
|
|
27
|
|
28 $this->type( $opts{type} )
|
|
29 or die IMPL::InvalidArgumentException->new('type');
|
|
30
|
|
31 $this->activation(
|
|
32 IMPL::Config::Descriptor::ParseActivation( $opts{activation} ) );
|
|
33 $this->args( $opts{args} ) if exists $opts{args};
|
|
34 $this->services( $opts{services} ) if exists $opts{services};
|
|
35
|
|
36 $this->_name( 'new {'
|
|
37 . IMPL::Config::Descriptor::ActivationToString( $this->activation )
|
|
38 . '} '
|
|
39 . $this->type );
|
|
40 }
|
|
41
|
|
42 sub Activate {
|
|
43 my ( $this, $context ) = @_;
|
|
44
|
416
|
45 my $instance;
|
|
46 $context->GuardScope(
|
|
47 $this->_name,
|
|
48 $this->services,
|
|
49 sub {
|
415
|
50
|
416
|
51 my $activation = $this->activation;
|
|
52 my $cache;
|
415
|
53
|
416
|
54 if ( $activation == IMPL::Config::Descriptor::ACTIVATE_SINGLETON ) {
|
|
55 $cache = $context->container->root->instances;
|
|
56 }
|
|
57 elsif (
|
|
58 $activation == IMPL::Config::Descriptor::ACTIVATE_CONTAINER )
|
|
59 {
|
|
60 $cache = $context->container->instances;
|
|
61 }
|
|
62 elsif ( $activation == IMPL::Config::Descriptor::ACTIVATE_CONTEXT )
|
|
63 {
|
|
64 $cache = $context->instances;
|
|
65 }
|
415
|
66
|
416
|
67 $instance = $cache->{ ref($this) } if $cache;
|
|
68 unless ($instance) {
|
|
69 $instance = $this->CreateInstance($context);
|
|
70 }
|
415
|
71
|
416
|
72 $cache->{ ref($this) } = $instance if $cache;
|
|
73 }
|
|
74 );
|
415
|
75
|
|
76 return $instance;
|
|
77 }
|
|
78
|
|
79 sub CreateInstance {
|
|
80 my ( $this, $context ) = @_;
|
|
81
|
|
82 my $class = $context > container->Require( $this->type );
|
|
83
|
|
84 my $args = $this->args ? $this->args->Activate($context) : undef;
|
|
85
|
|
86 if ( defined $args ) {
|
|
87 if ( isarray($args) ) {
|
|
88 return $class->new(@$args);
|
|
89 }
|
|
90 elsif ( ishash($args) ) {
|
|
91 return $class->new(%$args);
|
|
92 }
|
|
93 else {
|
|
94 return $class->new($args);
|
|
95 }
|
|
96 }
|
|
97 else {
|
|
98 return $class->new();
|
|
99 }
|
|
100 }
|
|
101
|
|
102 1;
|