renaming application_name -> catalyst_application
[catagits/Catalyst-Runtime.git] / lib / Catalyst / IOC / ConstructorInjection.pm
1 package Catalyst::IOC::ConstructorInjection;
2 use Moose;
3 use Bread::Board::Dependency;
4 use Try::Tiny;
5 use Catalyst::Utils ();
6
7 extends 'Bread::Board::ConstructorInjection';
8
9 sub BUILD {
10     my $self = shift;
11     $self->add_dependency(
12         __catalyst_config => Bread::Board::Dependency->new(
13             service_path => '/config'
14         )
15     );
16 }
17
18 has catalyst_component_name => (
19     is => 'ro',
20 );
21
22 has config => (
23     init_arg   => undef,
24     is         => 'ro',
25     isa        => 'HashRef',
26     writer     => '_set_config',
27     clearer    => '_clear_config',
28 );
29
30 around resolve_dependencies => sub {
31     my ($orig, $self, @args) = @_;
32     my %deps = $self->$orig(@args);
33     my $app_config = delete $deps{__catalyst_config};
34     my $conf_key = Catalyst::Utils::class2classsuffix($self->catalyst_component_name);
35     $self->_set_config($app_config->{$conf_key} || {});
36     return %deps;
37 };
38
39 sub get {
40     my $self = shift;
41     my $component   = $self->class;
42
43     my $params = $self->params;
44     my %config = (%{ $self->config || {} }, %{ $params });
45     $self->_clear_config;
46
47     my $app = $self->param('catalyst_application');
48
49     # Stash catalyst_component_name in the config here, so that custom COMPONENT
50     # methods also pass it.
51     $config{catalyst_component_name} = $self->catalyst_component_name;
52
53     unless ( $component->can( 'COMPONENT' ) ) {
54         # FIXME - make some deprecation warnings
55         return $component;
56     }
57
58     my $instance;
59     try {
60         $instance = $component->COMPONENT( $app, \%config );
61     }
62     catch {
63         Catalyst::Exception->throw(
64             message => qq/Couldn't instantiate component "$component", "$_"/
65         );
66     };
67
68     return $instance
69         if blessed $instance;
70
71     my $metaclass = Moose::Util::find_meta($component);
72     my $method_meta = $metaclass->find_method_by_name('COMPONENT');
73     my $component_method_from = $method_meta->associated_metaclass->name;
74     my $value = defined($instance) ? $instance : 'undef';
75     Catalyst::Exception->throw(
76         message =>
77         qq/Couldn't instantiate component "$component", COMPONENT method (from $component_method_from) didn't return an object-like value (value was $value)./
78     );
79 }
80
81 __PACKAGE__->meta->make_immutable;
82
83 no Moose; 1;
84
85 __END__
86
87 =pod
88
89 =head1 NAME
90
91 Catalyst::IOC::ConstructorInjection
92
93 =head1 SYNOPSIS
94
95 =head1 DESCRIPTION
96
97 =head1 AUTHORS
98
99 Catalyst Contributors, see Catalyst.pm
100
101 =head1 COPYRIGHT
102
103 This library is free software. You can redistribute it and/or modify it under
104 the same terms as Perl itself.
105
106 =cut