1 package Catalyst::IOC::Container;
5 use Data::Visitor::Callback;
6 use Catalyst::Utils ();
7 use Devel::InnerPackage ();
8 use Hash::Util qw/lock_hash/;
9 use MooseX::Types::LoadableClass qw/ LoadableClass /;
11 use Catalyst::IOC::BlockInjection;
12 use namespace::autoclean;
14 extends 'Bread::Board::Container';
16 has config_local_suffix => (
25 default => sub { +{} },
34 has substitutions => (
37 default => sub { +{} },
46 has sub_container_class => (
50 default => 'Catalyst::IOC::SubContainer',
52 new_sub_container => 'new',
57 my ( $self, $params ) = @_;
60 $self->${\"build_${_}_service"}
79 $self->add_sub_container(
80 $self->build_controller_subcontainer
83 # FIXME - the config should be merged at this point
84 my $config = $self->resolve( service => 'config' );
85 my $default_view = $params->{default_view} || $config->{default_view};
86 my $default_model = $params->{default_model} || $config->{default_model};
88 $self->add_sub_container(
89 $self->build_view_subcontainer(
90 default_component => $default_view,
94 $self->add_sub_container(
95 $self->build_model_subcontainer(
96 default_component => $default_model,
101 sub build_model_subcontainer {
104 return $self->new_sub_container( @_,
109 sub build_view_subcontainer {
112 return $self->new_sub_container( @_,
117 sub build_controller_subcontainer {
120 return $self->new_sub_container(
121 name => 'controller',
125 sub build_name_service {
128 return Bread::Board::Literal->new( name => 'name', value => $self->name );
131 sub build_driver_service {
134 return Bread::Board::Literal->new( name => 'driver', value => $self->driver );
137 sub build_file_service {
140 return Bread::Board::Literal->new( name => 'file', value => $self->file );
143 sub build_substitutions_service {
146 return Bread::Board::Literal->new( name => 'substitutions', value => $self->substitutions );
149 sub build_extensions_service {
152 return Bread::Board::BlockInjection->new(
153 name => 'extensions',
155 return \@{Config::Any->extensions};
160 sub build_prefix_service {
163 return Bread::Board::BlockInjection->new(
166 return Catalyst::Utils::appprefix( shift->param('name') );
168 dependencies => [ depends_on('name') ],
172 sub build_path_service {
175 return Bread::Board::BlockInjection->new(
180 return Catalyst::Utils::env_value( $s->param('name'), 'CONFIG' )
182 || $s->param('name')->path_to( $s->param('prefix') );
184 dependencies => [ depends_on('file'), depends_on('name'), depends_on('prefix') ],
188 sub build_config_service {
191 return Bread::Board::BlockInjection->new(
196 my $v = Data::Visitor::Callback->new(
198 return unless defined $_;
199 return $self->_config_substitutions( $s->param('name'), $s->param('substitutions'), $_ );
203 $v->visit( $s->param('raw_config') );
205 dependencies => [ depends_on('name'), depends_on('raw_config'), depends_on('substitutions') ],
209 sub build_raw_config_service {
212 return Bread::Board::BlockInjection->new(
213 name => 'raw_config',
217 my @global = @{$s->param('global_config')};
218 my @locals = @{$s->param('local_config')};
221 for my $cfg (@global, @locals) {
223 $config = Catalyst::Utils::merge_hashes( $config, $cfg->{$_} );
228 dependencies => [ depends_on('global_config'), depends_on('local_config') ],
232 sub build_global_files_service {
235 return Bread::Board::BlockInjection->new(
236 name => 'global_files',
240 my ( $path, $extension ) = @{$s->param('config_path')};
242 my @extensions = @{$s->param('extensions')};
246 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
249 @files = map { "$path.$_" } @extensions;
253 dependencies => [ depends_on('extensions'), depends_on('config_path') ],
257 sub build_local_files_service {
260 return Bread::Board::BlockInjection->new(
261 name => 'local_files',
265 my ( $path, $extension ) = @{$s->param('config_path')};
266 my $suffix = $s->param('config_local_suffix');
268 my @extensions = @{$s->param('extensions')};
272 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
273 $path =~ s{\.$extension}{_$suffix.$extension};
276 @files = map { "${path}_${suffix}.$_" } @extensions;
280 dependencies => [ depends_on('extensions'), depends_on('config_path'), depends_on('config_local_suffix') ],
284 sub build_global_config_service {
287 return Bread::Board::BlockInjection->new(
288 name => 'global_config',
292 return Config::Any->load_files({
293 files => $s->param('global_files'),
294 filter => \&_fix_syntax,
296 driver_args => $s->param('driver'),
299 dependencies => [ depends_on('global_files') ],
303 sub build_local_config_service {
306 return Bread::Board::BlockInjection->new(
307 name => 'local_config',
311 return Config::Any->load_files({
312 files => $s->param('local_files'),
313 filter => \&_fix_syntax,
315 driver_args => $s->param('driver'),
318 dependencies => [ depends_on('local_files') ],
322 sub build_config_path_service {
325 return Bread::Board::BlockInjection->new(
326 name => 'config_path',
330 my $path = $s->param('path');
331 my $prefix = $s->param('prefix');
333 my ( $extension ) = ( $path =~ m{\.(.{1,4})$} );
336 $path =~ s{[\/\\]$}{};
340 return [ $path, $extension ];
342 dependencies => [ depends_on('prefix'), depends_on('path') ],
346 sub build_config_local_suffix_service {
349 return Bread::Board::BlockInjection->new(
350 name => 'config_local_suffix',
353 my $suffix = Catalyst::Utils::env_value( $s->param('name'), 'CONFIG_LOCAL_SUFFIX' ) || $self->config_local_suffix;
357 dependencies => [ depends_on('name') ],
365 prefix => $_ eq 'Component' ? '' : $_ . '::',
366 values => delete $config->{ lc $_ } || delete $config->{ $_ }
368 grep { ref $config->{ lc $_ } || ref $config->{ $_ } }
369 qw( Component Model M View V Controller C Plugin )
372 foreach my $comp ( @components ) {
373 my $prefix = $comp->{ prefix };
374 foreach my $element ( keys %{ $comp->{ values } } ) {
375 $config->{ "$prefix$element" } = $comp->{ values }->{ $element };
380 sub _config_substitutions {
381 my ( $self, $name, $subs, $arg ) = @_;
383 $subs->{ HOME } ||= sub { shift->path_to( '' ); };
387 if (! defined($ENV{$v})) {
388 Catalyst::Exception->throw( message =>
389 "Missing environment variable: $v" );
395 $subs->{ path_to } ||= sub { shift->path_to( @_ ); };
396 $subs->{ literal } ||= sub { return $_[ 1 ]; };
397 my $subsre = join( '|', keys %$subs );
399 $arg =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $name, $2 ? split( /,/, $2 ) : () ) }eg;
403 sub get_component_from_sub_container {
404 my ( $self, $sub_container_name, $name, $c, @args ) = @_;
406 my $sub_container = $self->get_sub_container( $sub_container_name );
409 my $default = $sub_container->default_component;
411 return $sub_container->get_component( $default, $c, @args )
412 if $default && $sub_container->has_service( $default );
414 # FIXME - should I be calling $c->log->warn here?
415 # this is never a controller, so this is safe
416 $c->log->warn( "Calling \$c->$sub_container_name() is not supported unless you specify one of:" );
417 $c->log->warn( "* \$c->config(default_$sub_container_name => 'the name of the default $sub_container_name to use')" );
418 $c->log->warn( "* \$c->stash->{current_$sub_container_name} # the name of the view to use for this request" );
419 $c->log->warn( "* \$c->stash->{current_${sub_container_name}_instance} # the instance of the $sub_container_name to use for this request" );
424 return $sub_container->get_component_regexp( $name, $c, @args )
427 return $sub_container->get_component( $name, $c, @args )
428 if $sub_container->has_service( $name );
431 "Attempted to use $sub_container_name '$name', " .
432 "but it does not exist"
439 my ( $self, $component, $c, @args ) = @_;
440 my ( $type, $name ) = _get_component_type_name($component);
443 return $self->get_component_from_sub_container(
444 $type, $name, $c, @args
447 my $query = ref $component
452 for my $subcontainer_name (qw/model view controller/) {
453 my $subcontainer = $self->get_sub_container( $subcontainer_name );
454 my @components = $subcontainer->get_service_list;
455 @result = grep { m{$component} } @components;
457 return map { $subcontainer->get_component( $_, $c, @args ) } @result
461 # FIXME - I guess I shouldn't be calling $c->components here
462 # one last search for things like $c->comp(qr/::M::/)
463 @result = $self->find_component_regexp(
464 $c->components, $component, $c, @args
465 ) if !@result and ref $component;
467 # it expects an empty list on failed searches
471 sub find_component_regexp {
472 my ( $self, $components, $component, @args ) = @_;
475 my @components = grep { m{$component} } keys %{ $components };
478 my ($type, $name) = _get_component_type_name($_);
480 push @result, $self->get_component_from_sub_container(
488 # FIXME sorry for the name again :)
489 sub get_components_types {
493 for my $sub_container_name (qw/model view controller/) {
494 my $sub_container = $self->get_sub_container($sub_container_name);
495 for my $service ( $sub_container->get_service_list ) {
496 my $comp = $self->resolve(service => $service);
497 my $compname = ref $comp || $comp;
498 my $type = ref $comp ? 'instance' : 'class';
499 push @comps_types, [ $compname, $type ];
506 sub get_all_components {
511 map { $_ => $self->get_sub_container($_) } qw(model view controller)
514 for my $container (keys %$containers) {
515 for my $component ($containers->{$container}->get_service_list) {
516 my $comp = $containers->{$container}->resolve(
517 service => $component
519 my $comp_name = ref $comp || $comp;
520 $components{$comp_name} = $comp;
524 return lock_hash %components;
528 my ( $self, $component, $class ) = @_;
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 { $self->setup_component( $component, $class ) },
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);
563 # FIXME ugly and temporary
564 # Just moved it here the way it was, so we can work on it here in the container
565 sub setup_component {
566 my ( $self, $component, $class ) = @_;
568 unless ( $component->can( 'COMPONENT' ) ) {
572 # FIXME I know this isn't the "Dependency Injection" way of doing things,
574 my $suffix = Catalyst::Utils::class2classsuffix( $component );
575 my $config = $self->resolve(service => 'config')->{ $suffix } || {};
577 # Stash catalyst_component_name in the config here, so that custom COMPONENT
578 # methods also pass it. local to avoid pointlessly shitting in config
579 # for the debug screen, as $component is already the key name.
580 local $config->{catalyst_component_name} = $component;
582 my $instance = eval { $component->COMPONENT( $class, $config ); };
584 if ( my $error = $@ ) {
586 Catalyst::Exception->throw(
587 message => qq/Couldn't instantiate component "$component", "$error"/
590 elsif (!blessed $instance) {
591 my $metaclass = Moose::Util::find_meta($component);
592 my $method_meta = $metaclass->find_method_by_name('COMPONENT');
593 my $component_method_from = $method_meta->associated_metaclass->name;
594 my $value = defined($instance) ? $instance : 'undef';
595 Catalyst::Exception->throw(
597 qq/Couldn't instantiate component "$component", COMPONENT() method (from $component_method_from) didn't return an object-like value (value was $value)./
604 sub expand_component_module {
605 my ( $class, $module ) = @_;
606 return Devel::InnerPackage::list_packages( $module );
617 Catalyst::Container - IOC for Catalyst components
627 =head2 build_model_subcontainer
629 Container that stores all models.
631 =head2 build_view_subcontainer
633 Container that stores all views.
635 =head2 build_controller_subcontainer
637 Container that stores all controllers.
641 =head2 build_name_service
643 Name of the application.
645 =head2 build_driver_service
647 Config options passed directly to the driver being used.
649 =head2 build_file_service
653 =head2 build_substitutions_service
655 Executes all the substitutions in config. See L</_config_substitutions> method.
657 =head2 build_extensions_service
659 =head2 build_prefix_service
661 =head2 build_path_service
663 =head2 build_config_service
665 =head2 build_raw_config_service
667 =head2 build_global_files_service
669 =head2 build_local_files_service
671 =head2 build_global_config_service
673 =head2 build_local_config_service
675 =head2 build_config_path_service
677 =head2 build_config_local_suffix_service
679 Determines the suffix of files used to override the main config. By default
680 this value is C<local>, which will load C<myapp_local.conf>. The suffix can
681 be specified in the following order of preference:
685 =item * C<$ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }>
687 =item * C<$ENV{ CATALYST_CONFIG_LOCAL_SUFFIX }>
691 The first one of these values found replaces the default of C<local> in the
692 name of the local config file to be loaded.
694 For example, if C< $ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }> is set to C<testing>,
695 ConfigLoader will try and load C<myapp_testing.conf> instead of
698 =head2 get_component_from_sub_container($sub_container, $name, $c, @args)
700 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.
702 =head2 get_components_types
704 =head2 get_all_components
706 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.
710 Adds a component to the appropriate subcontainer. The subcontainer is guessed by the component name given.
712 =head2 find_component
714 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.
716 =head2 find_component_regexp
718 Finds components that match a given regexp. Used internally, by find_component.
720 =head2 setup_component
724 =head2 _config_substitutions
726 This method substitutes macros found with calls to a function. There are a
727 number of default macros:
731 =item * C<__HOME__> - replaced with C<$c-E<gt>path_to('')>
733 =item * C<__ENV(foo)__> - replaced with the value of C<$ENV{foo}>
735 =item * C<__path_to(foo/bar)__> - replaced with C<$c-E<gt>path_to('foo/bar')>
737 =item * C<__literal(__FOO__)__> - leaves __FOO__ alone (allows you to use
738 C<__DATA__> as a config value, for example)
742 The parameter list is split on comma (C<,>). You can override this method to
743 do your own string munging, or you can define your own macros in
744 C<MyApp-E<gt>config-E<gt>{ 'Plugin::ConfigLoader' }-E<gt>{ substitutions }>.
747 MyApp->config->{ 'Plugin::ConfigLoader' }->{ substitutions } = {
748 baz => sub { my $c = shift; qux( @_ ); }
751 The above will respond to C<__baz(x,y)__> in config strings.
753 =head2 $c->expand_component_module( $component, $setup_component_config )
755 Components found by C<locate_components> will be passed to this method, which
756 is expected to return a list of component (package) names to be set up.
762 Catalyst Contributors, see Catalyst.pm
766 This library is free software. You can redistribute it and/or modify it under
767 the same terms as Perl itself.