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 Module::Pluggable::Object ();
13 use namespace::autoclean;
15 extends 'Bread::Board::Container';
17 has config_local_suffix => (
26 default => sub { +{} },
35 has substitutions => (
38 default => sub { +{} },
47 has sub_container_class => (
51 default => 'Catalyst::IOC::SubContainer',
53 new_sub_container => 'new',
58 my ( $self, $params ) = @_;
61 $self->${\"build_${_}_service"}
80 $self->add_sub_container(
81 $self->build_controller_subcontainer
84 # FIXME - the config should be merged at this point
85 my $config = $self->resolve( service => 'config' );
86 my $default_view = $params->{default_view} || $config->{default_view};
87 my $default_model = $params->{default_model} || $config->{default_model};
89 $self->add_sub_container(
90 $self->build_view_subcontainer(
91 default_component => $default_view,
95 $self->add_sub_container(
96 $self->build_model_subcontainer(
97 default_component => $default_model,
102 sub build_model_subcontainer {
105 return $self->new_sub_container( @_,
110 sub build_view_subcontainer {
113 return $self->new_sub_container( @_,
118 sub build_controller_subcontainer {
121 return $self->new_sub_container(
122 name => 'controller',
126 sub build_name_service {
129 return Bread::Board::Literal->new( name => 'name', value => $self->name );
132 sub build_driver_service {
135 return Bread::Board::Literal->new( name => 'driver', value => $self->driver );
138 sub build_file_service {
141 return Bread::Board::Literal->new( name => 'file', value => $self->file );
144 sub build_substitutions_service {
147 return Bread::Board::Literal->new( name => 'substitutions', value => $self->substitutions );
150 sub build_extensions_service {
153 return Bread::Board::BlockInjection->new(
154 name => 'extensions',
156 return \@{Config::Any->extensions};
161 sub build_prefix_service {
164 return Bread::Board::BlockInjection->new(
167 return Catalyst::Utils::appprefix( shift->param('name') );
169 dependencies => [ depends_on('name') ],
173 sub build_path_service {
176 return Bread::Board::BlockInjection->new(
181 return Catalyst::Utils::env_value( $s->param('name'), 'CONFIG' )
183 || $s->param('name')->path_to( $s->param('prefix') );
185 dependencies => [ depends_on('file'), depends_on('name'), depends_on('prefix') ],
189 sub build_config_service {
192 return Bread::Board::BlockInjection->new(
197 my $v = Data::Visitor::Callback->new(
199 return unless defined $_;
200 return $self->_config_substitutions( $s->param('name'), $s->param('substitutions'), $_ );
204 $v->visit( $s->param('raw_config') );
206 dependencies => [ depends_on('name'), depends_on('raw_config'), depends_on('substitutions') ],
210 sub build_raw_config_service {
213 return Bread::Board::BlockInjection->new(
214 name => 'raw_config',
218 my @global = @{$s->param('global_config')};
219 my @locals = @{$s->param('local_config')};
222 for my $cfg (@global, @locals) {
224 $config = Catalyst::Utils::merge_hashes( $config, $cfg->{$_} );
229 dependencies => [ depends_on('global_config'), depends_on('local_config') ],
233 sub build_global_files_service {
236 return Bread::Board::BlockInjection->new(
237 name => 'global_files',
241 my ( $path, $extension ) = @{$s->param('config_path')};
243 my @extensions = @{$s->param('extensions')};
247 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
250 @files = map { "$path.$_" } @extensions;
254 dependencies => [ depends_on('extensions'), depends_on('config_path') ],
258 sub build_local_files_service {
261 return Bread::Board::BlockInjection->new(
262 name => 'local_files',
266 my ( $path, $extension ) = @{$s->param('config_path')};
267 my $suffix = $s->param('config_local_suffix');
269 my @extensions = @{$s->param('extensions')};
273 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
274 $path =~ s{\.$extension}{_$suffix.$extension};
277 @files = map { "${path}_${suffix}.$_" } @extensions;
281 dependencies => [ depends_on('extensions'), depends_on('config_path'), depends_on('config_local_suffix') ],
285 sub build_global_config_service {
288 return Bread::Board::BlockInjection->new(
289 name => 'global_config',
293 return Config::Any->load_files({
294 files => $s->param('global_files'),
295 filter => \&_fix_syntax,
297 driver_args => $s->param('driver'),
300 dependencies => [ depends_on('global_files') ],
304 sub build_local_config_service {
307 return Bread::Board::BlockInjection->new(
308 name => 'local_config',
312 return Config::Any->load_files({
313 files => $s->param('local_files'),
314 filter => \&_fix_syntax,
316 driver_args => $s->param('driver'),
319 dependencies => [ depends_on('local_files') ],
323 sub build_config_path_service {
326 return Bread::Board::BlockInjection->new(
327 name => 'config_path',
331 my $path = $s->param('path');
332 my $prefix = $s->param('prefix');
334 my ( $extension ) = ( $path =~ m{\.(.{1,4})$} );
337 $path =~ s{[\/\\]$}{};
341 return [ $path, $extension ];
343 dependencies => [ depends_on('prefix'), depends_on('path') ],
347 sub build_config_local_suffix_service {
350 return Bread::Board::BlockInjection->new(
351 name => 'config_local_suffix',
354 my $suffix = Catalyst::Utils::env_value( $s->param('name'), 'CONFIG_LOCAL_SUFFIX' ) || $self->config_local_suffix;
358 dependencies => [ depends_on('name') ],
366 prefix => $_ eq 'Component' ? '' : $_ . '::',
367 values => delete $config->{ lc $_ } || delete $config->{ $_ }
369 grep { ref $config->{ lc $_ } || ref $config->{ $_ } }
370 qw( Component Model M View V Controller C Plugin )
373 foreach my $comp ( @components ) {
374 my $prefix = $comp->{ prefix };
375 foreach my $element ( keys %{ $comp->{ values } } ) {
376 $config->{ "$prefix$element" } = $comp->{ values }->{ $element };
381 sub _config_substitutions {
382 my ( $self, $name, $subs, $arg ) = @_;
384 $subs->{ HOME } ||= sub { shift->path_to( '' ); };
388 if (! defined($ENV{$v})) {
389 Catalyst::Exception->throw( message =>
390 "Missing environment variable: $v" );
396 $subs->{ path_to } ||= sub { shift->path_to( @_ ); };
397 $subs->{ literal } ||= sub { return $_[ 1 ]; };
398 my $subsre = join( '|', keys %$subs );
400 $arg =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $name, $2 ? split( /,/, $2 ) : () ) }eg;
404 sub get_component_from_sub_container {
405 my ( $self, $sub_container_name, $name, $c, @args ) = @_;
407 my $sub_container = $self->get_sub_container( $sub_container_name );
410 my $default = $sub_container->default_component;
412 return $sub_container->get_component( $default, $c, @args )
413 if $default && $sub_container->has_service( $default );
415 # FIXME - should I be calling $c->log->warn here?
416 # this is never a controller, so this is safe
417 $c->log->warn( "Calling \$c->$sub_container_name() is not supported unless you specify one of:" );
418 $c->log->warn( "* \$c->config(default_$sub_container_name => 'the name of the default $sub_container_name to use')" );
419 $c->log->warn( "* \$c->stash->{current_$sub_container_name} # the name of the view to use for this request" );
420 $c->log->warn( "* \$c->stash->{current_${sub_container_name}_instance} # the instance of the $sub_container_name to use for this request" );
425 return $sub_container->get_component_regexp( $name, $c, @args )
428 return $sub_container->get_component( $name, $c, @args )
429 if $sub_container->has_service( $name );
432 "Attempted to use $sub_container_name '$name', " .
433 "but it does not exist"
440 my ( $self, $component, $c, @args ) = @_;
441 my ( $type, $name ) = _get_component_type_name($component);
444 return $self->get_component_from_sub_container(
445 $type, $name, $c, @args
448 my $query = ref $component
453 for my $subcontainer_name (qw/model view controller/) {
454 my $subcontainer = $self->get_sub_container( $subcontainer_name );
455 my @components = $subcontainer->get_service_list;
456 @result = grep { m{$component} } @components;
458 return map { $subcontainer->get_component( $_, $c, @args ) } @result
462 # FIXME - I guess I shouldn't be calling $c->components here
463 # one last search for things like $c->comp(qr/::M::/)
464 @result = $self->find_component_regexp(
465 $c->components, $component, $c, @args
466 ) if !@result and ref $component;
468 # it expects an empty list on failed searches
472 sub find_component_regexp {
473 my ( $self, $components, $component, @args ) = @_;
476 my @components = grep { m{$component} } keys %{ $components };
479 my ($type, $name) = _get_component_type_name($_);
481 push @result, $self->get_component_from_sub_container(
489 # FIXME sorry for the name again :)
490 sub get_components_types {
494 for my $sub_container_name (qw/model view controller/) {
495 my $sub_container = $self->get_sub_container($sub_container_name);
496 for my $service ( $sub_container->get_service_list ) {
497 my $comp = $self->resolve(service => $service);
498 my $compname = ref $comp || $comp;
499 my $type = ref $comp ? 'instance' : 'class';
500 push @comps_types, [ $compname, $type ];
507 sub get_all_components {
512 map { $_ => $self->get_sub_container($_) } qw(model view controller)
515 for my $container (keys %$containers) {
516 for my $component ($containers->{$container}->get_service_list) {
517 my $comp = $containers->{$container}->resolve(
518 service => $component
520 my $comp_name = ref $comp || $comp;
521 $components{$comp_name} = $comp;
525 return lock_hash %components;
529 my ( $self, $component, $class ) = @_;
530 my ( $type, $name ) = _get_component_type_name($component);
534 $self->get_sub_container($type)->add_service(
535 Catalyst::IOC::BlockInjection->new(
537 block => sub { $self->setup_component( $component, $class ) },
542 # FIXME: should this sub exist?
543 # should it be moved to Catalyst::Utils,
544 # or replaced by something already existing there?
545 sub _get_component_type_name {
546 my ( $component ) = @_;
548 my @parts = split /::/, $component;
550 while (my $type = shift @parts) {
551 return ('controller', join '::', @parts)
552 if $type =~ /^(c|controller)$/i;
554 return ('model', join '::', @parts)
555 if $type =~ /^(m|model)$/i;
557 return ('view', join '::', @parts)
558 if $type =~ /^(v|view)$/i;
561 return (undef, $component);
564 # FIXME ugly and temporary
565 # Just moved it here the way it was, so we can work on it here in the container
566 sub setup_component {
567 my ( $self, $component, $class ) = @_;
569 unless ( $component->can( 'COMPONENT' ) ) {
573 # FIXME I know this isn't the "Dependency Injection" way of doing things,
575 my $suffix = Catalyst::Utils::class2classsuffix( $component );
576 my $config = $self->resolve(service => 'config')->{ $suffix } || {};
578 # Stash catalyst_component_name in the config here, so that custom COMPONENT
579 # methods also pass it. local to avoid pointlessly shitting in config
580 # for the debug screen, as $component is already the key name.
581 local $config->{catalyst_component_name} = $component;
583 my $instance = eval { $component->COMPONENT( $class, $config ); };
585 if ( my $error = $@ ) {
587 Catalyst::Exception->throw(
588 message => qq/Couldn't instantiate component "$component", "$error"/
591 elsif (!blessed $instance) {
592 my $metaclass = Moose::Util::find_meta($component);
593 my $method_meta = $metaclass->find_method_by_name('COMPONENT');
594 my $component_method_from = $method_meta->associated_metaclass->name;
595 my $value = defined($instance) ? $instance : 'undef';
596 Catalyst::Exception->throw(
598 qq/Couldn't instantiate component "$component", COMPONENT() method (from $component_method_from) didn't return an object-like value (value was $value)./
605 sub expand_component_module {
606 my ( $class, $module ) = @_;
607 return Devel::InnerPackage::list_packages( $module );
610 sub locate_components {
611 my ( $self, $class, $config ) = @_;
613 my @paths = qw( ::Controller ::C ::Model ::M ::View ::V );
615 my $locator = Module::Pluggable::Object->new(
616 search_path => [ map { s/^(?=::)/$class/; $_; } @paths ],
620 # XXX think about ditching this sort entirely
621 my @comps = sort { length $a <=> length $b } $locator->plugins;
626 sub setup_components {
627 my ( $self, $class ) = @_;
629 # FIXME - should I get config as an argument, and throw the exception in
631 my $config = $self->resolve(service => 'config')->{ setup_components };
633 Catalyst::Exception->throw(
634 qq{You are using search_extra config option. That option is\n} .
635 qq{deprecated, please refer to the documentation for\n} .
636 qq{other ways of achieving the same results.\n}
637 ) if delete $config->{ search_extra };
639 my @comps = $self->locate_components( $class, $config );
640 my %comps = map { $_ => 1 } @comps;
642 my $deprecatedcatalyst_component_names = grep { /::[CMV]::/ } @comps;
643 $class->log->warn(qq{Your application is using the deprecated ::[MVC]:: type naming scheme.\n}.
644 qq{Please switch your class names to ::Model::, ::View:: and ::Controller: as appropriate.\n}
645 ) if $deprecatedcatalyst_component_names;
647 for my $component ( @comps ) {
649 # We pass ignore_loaded here so that overlay files for (e.g.)
650 # Model::DBI::Schema sub-classes are loaded - if it's in @comps
651 # we know M::P::O found a file on disk so this is safe
653 Catalyst::Utils::ensure_class_loaded( $component, { ignore_loaded => 1 } );
656 for my $component (@comps) {
657 $self->add_component( $component, $class );
658 # FIXME - $instance->expand_modules() is broken
659 my @expanded_components = $self->expand_component_module( $component );
660 for my $component (@expanded_components) {
661 next if $comps{$component};
663 # FIXME - Why is it inside the for loop? It makes no sense
664 $deprecatedcatalyst_component_names = grep { /::[CMV]::/ } @expanded_components;
666 # FIXME - should I be calling warn here?
667 $class->log->warn(qq{Your application is using the deprecated ::[MVC]:: type naming scheme.\n}.
668 qq{Please switch your class names to ::Model::, ::View:: and ::Controller: as appropriate.\n}
669 ) if $deprecatedcatalyst_component_names;
671 $self->add_component( $component, $class );
675 $self->get_sub_container('model')->make_single_default;
676 $self->get_sub_container('view')->make_single_default;
687 Catalyst::Container - IOC for Catalyst components
697 =head2 build_model_subcontainer
699 Container that stores all models.
701 =head2 build_view_subcontainer
703 Container that stores all views.
705 =head2 build_controller_subcontainer
707 Container that stores all controllers.
711 =head2 build_name_service
713 Name of the application.
715 =head2 build_driver_service
717 Config options passed directly to the driver being used.
719 =head2 build_file_service
723 =head2 build_substitutions_service
725 Executes all the substitutions in config. See L</_config_substitutions> method.
727 =head2 build_extensions_service
729 =head2 build_prefix_service
731 =head2 build_path_service
733 =head2 build_config_service
735 =head2 build_raw_config_service
737 =head2 build_global_files_service
739 =head2 build_local_files_service
741 =head2 build_global_config_service
743 =head2 build_local_config_service
745 =head2 build_config_path_service
747 =head2 build_config_local_suffix_service
749 Determines the suffix of files used to override the main config. By default
750 this value is C<local>, which will load C<myapp_local.conf>. The suffix can
751 be specified in the following order of preference:
755 =item * C<$ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }>
757 =item * C<$ENV{ CATALYST_CONFIG_LOCAL_SUFFIX }>
761 The first one of these values found replaces the default of C<local> in the
762 name of the local config file to be loaded.
764 For example, if C< $ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }> is set to C<testing>,
765 ConfigLoader will try and load C<myapp_testing.conf> instead of
768 =head2 get_component_from_sub_container($sub_container, $name, $c, @args)
770 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.
772 =head2 get_components_types
774 =head2 get_all_components
776 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.
780 Adds a component to the appropriate subcontainer. The subcontainer is guessed by the component name given.
782 =head2 find_component
784 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.
786 =head2 find_component_regexp
788 Finds components that match a given regexp. Used internally, by find_component.
790 =head2 setup_component
794 =head2 _config_substitutions
796 This method substitutes macros found with calls to a function. There are a
797 number of default macros:
801 =item * C<__HOME__> - replaced with C<$c-E<gt>path_to('')>
803 =item * C<__ENV(foo)__> - replaced with the value of C<$ENV{foo}>
805 =item * C<__path_to(foo/bar)__> - replaced with C<$c-E<gt>path_to('foo/bar')>
807 =item * C<__literal(__FOO__)__> - leaves __FOO__ alone (allows you to use
808 C<__DATA__> as a config value, for example)
812 The parameter list is split on comma (C<,>). You can override this method to
813 do your own string munging, or you can define your own macros in
814 C<MyApp-E<gt>config-E<gt>{ 'Plugin::ConfigLoader' }-E<gt>{ substitutions }>.
817 MyApp->config->{ 'Plugin::ConfigLoader' }->{ substitutions } = {
818 baz => sub { my $c = shift; qux( @_ ); }
821 The above will respond to C<__baz(x,y)__> in config strings.
823 =head2 $c->expand_component_module( $component, $setup_component_config )
825 Components found by C<locate_components> will be passed to this method, which
826 is expected to return a list of component (package) names to be set up.
828 =head2 locate_components( $setup_component_config )
830 This method is meant to provide a list of component modules that should be
831 setup for the application. By default, it will use L<Module::Pluggable>.
833 Specify a C<setup_components> config option to pass additional options directly
834 to L<Module::Pluggable>.
838 Catalyst Contributors, see Catalyst.pm
842 This library is free software. You can redistribute it and/or modify it under
843 the same terms as Perl itself.