1 package Catalyst::IOC::Container;
5 use Data::Visitor::Callback;
6 use Catalyst::Utils ();
7 use Hash::Util qw/lock_hash/;
8 use MooseX::Types::LoadableClass qw/ LoadableClass /;
9 use Catalyst::IOC::BlockInjection;
10 use namespace::autoclean;
12 extends 'Bread::Board::Container';
14 has config_local_suffix => (
23 default => sub { +{} },
32 has substitutions => (
35 default => sub { +{} },
44 has sub_container_class => (
48 default => 'Catalyst::IOC::SubContainer',
50 new_sub_container => 'new',
55 my ( $self, $params ) = @_;
58 $self->${\"build_${_}_service"}
77 $self->add_sub_container(
78 $self->build_controller_subcontainer
81 # FIXME - the config should be merged at this point
82 my $config = $self->resolve( service => 'config' );
83 my $default_view = $params->{default_view} || $config->{default_view};
84 my $default_model = $params->{default_model} || $config->{default_model};
86 $self->add_sub_container(
87 $self->build_view_subcontainer(
88 default_component => $default_view,
92 $self->add_sub_container(
93 $self->build_model_subcontainer(
94 default_component => $default_model,
99 sub build_model_subcontainer {
102 return $self->new_sub_container( @_,
107 sub build_view_subcontainer {
110 return $self->new_sub_container( @_,
115 sub build_controller_subcontainer {
118 return $self->new_sub_container(
119 name => 'controller',
123 sub build_name_service {
126 return Bread::Board::Literal->new( name => 'name', value => $self->name );
129 sub build_driver_service {
132 return Bread::Board::Literal->new( name => 'driver', value => $self->driver );
135 sub build_file_service {
138 return Bread::Board::Literal->new( name => 'file', value => $self->file );
141 sub build_substitutions_service {
144 return Bread::Board::Literal->new( name => 'substitutions', value => $self->substitutions );
147 sub build_extensions_service {
150 return Bread::Board::BlockInjection->new(
151 name => 'extensions',
153 return \@{Config::Any->extensions};
158 sub build_prefix_service {
161 return Bread::Board::BlockInjection->new(
164 return Catalyst::Utils::appprefix( shift->param('name') );
166 dependencies => [ depends_on('name') ],
170 sub build_path_service {
173 return Bread::Board::BlockInjection->new(
178 return Catalyst::Utils::env_value( $s->param('name'), 'CONFIG' )
180 || $s->param('name')->path_to( $s->param('prefix') );
182 dependencies => [ depends_on('file'), depends_on('name'), depends_on('prefix') ],
186 sub build_config_service {
189 return Bread::Board::BlockInjection->new(
194 my $v = Data::Visitor::Callback->new(
196 return unless defined $_;
197 return $self->_config_substitutions( $s->param('name'), $s->param('substitutions'), $_ );
201 $v->visit( $s->param('raw_config') );
203 dependencies => [ depends_on('name'), depends_on('raw_config'), depends_on('substitutions') ],
207 sub build_raw_config_service {
210 return Bread::Board::BlockInjection->new(
211 name => 'raw_config',
215 my @global = @{$s->param('global_config')};
216 my @locals = @{$s->param('local_config')};
219 for my $cfg (@global, @locals) {
221 $config = Catalyst::Utils::merge_hashes( $config, $cfg->{$_} );
226 dependencies => [ depends_on('global_config'), depends_on('local_config') ],
230 sub build_global_files_service {
233 return Bread::Board::BlockInjection->new(
234 name => 'global_files',
238 my ( $path, $extension ) = @{$s->param('config_path')};
240 my @extensions = @{$s->param('extensions')};
244 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
247 @files = map { "$path.$_" } @extensions;
251 dependencies => [ depends_on('extensions'), depends_on('config_path') ],
255 sub build_local_files_service {
258 return Bread::Board::BlockInjection->new(
259 name => 'local_files',
263 my ( $path, $extension ) = @{$s->param('config_path')};
264 my $suffix = $s->param('config_local_suffix');
266 my @extensions = @{$s->param('extensions')};
270 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
271 $path =~ s{\.$extension}{_$suffix.$extension};
274 @files = map { "${path}_${suffix}.$_" } @extensions;
278 dependencies => [ depends_on('extensions'), depends_on('config_path'), depends_on('config_local_suffix') ],
282 sub build_global_config_service {
285 return Bread::Board::BlockInjection->new(
286 name => 'global_config',
290 return Config::Any->load_files({
291 files => $s->param('global_files'),
292 filter => \&_fix_syntax,
294 driver_args => $s->param('driver'),
297 dependencies => [ depends_on('global_files') ],
301 sub build_local_config_service {
304 return Bread::Board::BlockInjection->new(
305 name => 'local_config',
309 return Config::Any->load_files({
310 files => $s->param('local_files'),
311 filter => \&_fix_syntax,
313 driver_args => $s->param('driver'),
316 dependencies => [ depends_on('local_files') ],
320 sub build_config_path_service {
323 return Bread::Board::BlockInjection->new(
324 name => 'config_path',
328 my $path = $s->param('path');
329 my $prefix = $s->param('prefix');
331 my ( $extension ) = ( $path =~ m{\.(.{1,4})$} );
334 $path =~ s{[\/\\]$}{};
338 return [ $path, $extension ];
340 dependencies => [ depends_on('prefix'), depends_on('path') ],
344 sub build_config_local_suffix_service {
347 return Bread::Board::BlockInjection->new(
348 name => 'config_local_suffix',
351 my $suffix = Catalyst::Utils::env_value( $s->param('name'), 'CONFIG_LOCAL_SUFFIX' ) || $self->config_local_suffix;
355 dependencies => [ depends_on('name') ],
363 prefix => $_ eq 'Component' ? '' : $_ . '::',
364 values => delete $config->{ lc $_ } || delete $config->{ $_ }
366 grep { ref $config->{ lc $_ } || ref $config->{ $_ } }
367 qw( Component Model M View V Controller C Plugin )
370 foreach my $comp ( @components ) {
371 my $prefix = $comp->{ prefix };
372 foreach my $element ( keys %{ $comp->{ values } } ) {
373 $config->{ "$prefix$element" } = $comp->{ values }->{ $element };
378 sub _config_substitutions {
379 my ( $self, $name, $subs, $arg ) = @_;
381 $subs->{ HOME } ||= sub { shift->path_to( '' ); };
385 if (! defined($ENV{$v})) {
386 Catalyst::Exception->throw( message =>
387 "Missing environment variable: $v" );
393 $subs->{ path_to } ||= sub { shift->path_to( @_ ); };
394 $subs->{ literal } ||= sub { return $_[ 1 ]; };
395 my $subsre = join( '|', keys %$subs );
397 $arg =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $name, $2 ? split( /,/, $2 ) : () ) }eg;
401 sub get_component_from_sub_container {
402 my ( $self, $sub_container_name, $name, $c, @args ) = @_;
404 my $sub_container = $self->get_sub_container( $sub_container_name );
407 my $default = $sub_container->default_component;
409 return $sub_container->get_component( $default, $c, @args )
410 if $default && $sub_container->has_service( $default );
412 # FIXME - should I be calling $c->log->warn here?
413 # this is never a controller, so this is safe
414 $c->log->warn( "Calling \$c->$sub_container_name() is not supported unless you specify one of:" );
415 $c->log->warn( "* \$c->config(default_$sub_container_name => 'the name of the default $sub_container_name to use')" );
416 $c->log->warn( "* \$c->stash->{current_$sub_container_name} # the name of the view to use for this request" );
417 $c->log->warn( "* \$c->stash->{current_${sub_container_name}_instance} # the instance of the $sub_container_name to use for this request" );
422 return $sub_container->get_component_regexp( $name, $c, @args )
425 return $sub_container->get_component( $name, $c, @args )
426 if $sub_container->has_service( $name );
429 "Attempted to use $sub_container_name '$name', " .
430 "but it does not exist"
437 my ( $self, $component, $c, @args ) = @_;
438 my ( $type, $name ) = _get_component_type_name($component);
441 return $self->get_component_from_sub_container(
442 $type, $name, $c, @args
445 my $query = ref $component
450 for my $subcontainer_name (qw/model view controller/) {
451 my $subcontainer = $self->get_sub_container( $subcontainer_name );
452 my @components = $subcontainer->get_service_list;
453 @result = grep { m{$component} } @components;
455 return map { $subcontainer->get_component( $_, $c, @args ) } @result
459 # FIXME - I guess I shouldn't be calling $c->components here
460 # one last search for things like $c->comp(qr/::M::/)
461 @result = $self->find_component_regexp(
462 $c->components, $component, $c, @args
463 ) if !@result and ref $component;
465 # it expects an empty list on failed searches
469 sub find_component_regexp {
470 my ( $self, $components, $component, @args ) = @_;
473 my @components = grep { m{$component} } keys %{ $components };
476 my ($type, $name) = _get_component_type_name($_);
478 push @result, $self->get_component_from_sub_container(
486 # FIXME sorry for the name again :)
487 sub get_components_types {
491 for my $sub_container_name (qw/model view controller/) {
492 my $sub_container = $self->get_sub_container($sub_container_name);
493 for my $service ( $sub_container->get_service_list ) {
494 my $comp = $self->resolve(service => $service);
495 my $compname = ref $comp || $comp;
496 my $type = ref $comp ? 'instance' : 'class';
497 push @comps_types, [ $compname, $type ];
504 sub get_all_components {
509 map { $_ => $self->get_sub_container($_) } qw(model view controller)
512 for my $container (keys %$containers) {
513 for my $component ($containers->{$container}->get_service_list) {
514 my $comp = $containers->{$container}->resolve(
515 service => $component
517 my $comp_name = ref $comp || $comp;
518 $components{$comp_name} = $comp;
522 return lock_hash %components;
526 # FIXME I'm aware it shouldn't be getting $instance as an argument
527 # and that setup_component should be removed. This is temporary
528 my ( $self, $component, $instance ) = @_;
529 my ( $type, $name ) = _get_component_type_name($component);
533 $self->get_sub_container($type)->add_service(
534 Catalyst::IOC::BlockInjection->new(
536 block => sub { $instance },
541 # FIXME: should this sub exist?
542 # should it be moved to Catalyst::Utils,
543 # or replaced by something already existing there?
544 sub _get_component_type_name {
545 my ( $component ) = @_;
547 my @parts = split /::/, $component;
549 while (my $type = shift @parts) {
550 return ('controller', join '::', @parts)
551 if $type =~ /^(c|controller)$/i;
553 return ('model', join '::', @parts)
554 if $type =~ /^(m|model)$/i;
556 return ('view', join '::', @parts)
557 if $type =~ /^(v|view)$/i;
560 return (undef, $component);
571 Catalyst::Container - IOC for Catalyst components
581 =head2 build_model_subcontainer
583 Container that stores all models.
585 =head2 build_view_subcontainer
587 Container that stores all views.
589 =head2 build_controller_subcontainer
591 Container that stores all controllers.
595 =head2 build_name_service
597 Name of the application.
599 =head2 build_driver_service
601 Config options passed directly to the driver being used.
603 =head2 build_file_service
607 =head2 build_substitutions_service
609 Executes all the substitutions in config. See L</_config_substitutions> method.
611 =head2 build_extensions_service
613 =head2 build_prefix_service
615 =head2 build_path_service
617 =head2 build_config_service
619 =head2 build_raw_config_service
621 =head2 build_global_files_service
623 =head2 build_local_files_service
625 =head2 build_global_config_service
627 =head2 build_local_config_service
629 =head2 build_config_path_service
631 =head2 build_config_local_suffix_service
633 Determines the suffix of files used to override the main config. By default
634 this value is C<local>, which will load C<myapp_local.conf>. The suffix can
635 be specified in the following order of preference:
639 =item * C<$ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }>
641 =item * C<$ENV{ CATALYST_CONFIG_LOCAL_SUFFIX }>
645 The first one of these values found replaces the default of C<local> in the
646 name of the local config file to be loaded.
648 For example, if C< $ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }> is set to C<testing>,
649 ConfigLoader will try and load C<myapp_testing.conf> instead of
652 =head2 get_component_from_sub_container($sub_container, $name, $c, @args)
654 Looks for components in a given subcontainer (such as controller, model or view), and returns the searched component. If $name is undef, it returns the default component (such as default_view, if $sub_container is 'view'). If $name is a regexp, it returns an array of matching components. Otherwise, it looks for the component with name $name.
656 =head2 get_components_types
658 =head2 get_all_components
660 Fetches all the components, in each of the sub_containers model, view and controller, and returns a readonly hash. The keys are the class names, and the values are the blessed objects. This is what is returned by $c->components.
664 Adds a component to the appropriate subcontainer. The subcontainer is guessed by the component name given.
666 =head2 find_component
668 Searches for components in all containers. If $component is the full class name, the subcontainer is guessed, and it gets the searched component in there. Otherwise, it looks for a component with that name in all subcontainers. If $component is a regexp, it calls the method below, find_component_regexp, and matches all components against that regexp.
670 =head2 find_component_regexp
672 Finds components that match a given regexp. Used internally, by find_component.
676 =head2 _config_substitutions
678 This method substitutes macros found with calls to a function. There are a
679 number of default macros:
683 =item * C<__HOME__> - replaced with C<$c-E<gt>path_to('')>
685 =item * C<__ENV(foo)__> - replaced with the value of C<$ENV{foo}>
687 =item * C<__path_to(foo/bar)__> - replaced with C<$c-E<gt>path_to('foo/bar')>
689 =item * C<__literal(__FOO__)__> - leaves __FOO__ alone (allows you to use
690 C<__DATA__> as a config value, for example)
694 The parameter list is split on comma (C<,>). You can override this method to
695 do your own string munging, or you can define your own macros in
696 C<MyApp-E<gt>config-E<gt>{ 'Plugin::ConfigLoader' }-E<gt>{ substitutions }>.
699 MyApp->config->{ 'Plugin::ConfigLoader' }->{ substitutions } = {
700 baz => sub { my $c = shift; qux( @_ ); }
703 The above will respond to C<__baz(x,y)__> in config strings.
707 Catalyst Contributors, see Catalyst.pm
711 This library is free software. You can redistribute it and/or modify it under
712 the same terms as Perl itself.