1 package Catalyst::IOC::Container;
5 use Data::Visitor::Callback;
6 use Catalyst::Utils ();
7 use List::Util qw(first);
8 use Devel::InnerPackage ();
9 use Hash::Util qw/lock_hash/;
10 use MooseX::Types::LoadableClass qw/ LoadableClass /;
12 use Catalyst::IOC::BlockInjection;
13 use Catalyst::IOC::ConstructorInjection;
14 use Module::Pluggable::Object ();
15 use namespace::autoclean;
17 extends 'Bread::Board::Container';
19 has config_local_suffix => (
28 default => sub { +{} },
37 has substitutions => (
40 default => sub { +{} },
43 has application_name => (
49 has sub_container_class => (
53 default => 'Catalyst::IOC::SubContainer',
55 new_sub_container => 'new',
60 my ( $self, $params ) = @_;
63 $self->${\"build_${_}_service"}
84 my $config = $self->resolve( service => 'config' );
86 # don't force default_component to be undef if the config wasn't set
87 my @default_view = $config->{default_view}
88 ? ( default_component => $config->{default_view} )
91 my @default_model = $config->{default_model}
92 ? ( default_component => $config->{default_model} )
96 $self->add_sub_container(
97 $self->build_component_subcontainer
100 $self->add_sub_container(
101 $self->build_controller_subcontainer
104 $self->add_sub_container(
105 $self->build_view_subcontainer( @default_view )
108 $self->add_sub_container(
109 $self->build_model_subcontainer( @default_model )
114 my $class = ref $self;
115 warn("In build $class");
116 ${ $class . '::customise_container' }->($self)
117 if ${ $class . '::customise_container' };
121 sub build_model_subcontainer {
124 return $self->new_sub_container( @_,
129 sub build_view_subcontainer {
132 return $self->new_sub_container( @_,
137 sub build_controller_subcontainer {
140 return $self->new_sub_container(
141 name => 'controller',
145 sub build_component_subcontainer {
148 return Bread::Board::Container->new(
153 sub build_application_name_service {
156 return Bread::Board::Literal->new( name => 'application_name', value => $self->application_name );
159 sub build_driver_service {
162 return Bread::Board::Literal->new( name => 'driver', value => $self->driver );
165 sub build_file_service {
168 return Bread::Board::Literal->new( name => 'file', value => $self->file );
171 sub build_substitutions_service {
174 return Bread::Board::Literal->new( name => 'substitutions', value => $self->substitutions );
177 sub build_extensions_service {
180 return Bread::Board::BlockInjection->new(
181 lifecycle => 'Singleton',
182 name => 'extensions',
184 return \@{Config::Any->extensions};
189 sub build_prefix_service {
192 return Bread::Board::BlockInjection->new(
193 lifecycle => 'Singleton',
196 return Catalyst::Utils::appprefix( shift->param('application_name') );
198 dependencies => [ depends_on('application_name') ],
202 sub build_path_service {
205 return Bread::Board::BlockInjection->new(
206 lifecycle => 'Singleton',
211 return Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG' )
213 || $s->param('application_name')->path_to( $s->param('prefix') );
215 dependencies => [ depends_on('file'), depends_on('application_name'), depends_on('prefix') ],
219 sub build_config_service {
222 return Bread::Board::BlockInjection->new(
223 lifecycle => 'Singleton',
228 my $v = Data::Visitor::Callback->new(
230 return unless defined $_;
231 return $self->_config_substitutions( $s->param('application_name'), $s->param('substitutions'), $_ );
235 $v->visit( $s->param('raw_config') );
237 dependencies => [ depends_on('application_name'), depends_on('raw_config'), depends_on('substitutions') ],
241 sub build_raw_config_service {
244 return Bread::Board::BlockInjection->new(
245 lifecycle => 'Singleton',
246 name => 'raw_config',
250 my @global = @{$s->param('global_config')};
251 my @locals = @{$s->param('local_config')};
253 my $config = $s->param('class_config');
255 for my $cfg (@global, @locals) {
257 $config = Catalyst::Utils::merge_hashes( $config, $cfg->{$_} );
263 dependencies => [ depends_on('global_config'), depends_on('local_config'), depends_on('class_config') ],
267 sub build_global_files_service {
270 return Bread::Board::BlockInjection->new(
271 lifecycle => 'Singleton',
272 name => 'global_files',
276 my ( $path, $extension ) = @{$s->param('config_path')};
278 my @extensions = @{$s->param('extensions')};
282 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
285 @files = map { "$path.$_" } @extensions;
289 dependencies => [ depends_on('extensions'), depends_on('config_path') ],
293 sub build_local_files_service {
296 return Bread::Board::BlockInjection->new(
297 lifecycle => 'Singleton',
298 name => 'local_files',
302 my ( $path, $extension ) = @{$s->param('config_path')};
303 my $suffix = $s->param('config_local_suffix');
305 my @extensions = @{$s->param('extensions')};
309 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
310 $path =~ s{\.$extension}{_$suffix.$extension};
313 @files = map { "${path}_${suffix}.$_" } @extensions;
317 dependencies => [ depends_on('extensions'), depends_on('config_path'), depends_on('config_local_suffix') ],
321 sub build_class_config_service {
324 return Bread::Board::BlockInjection->new(
325 lifecycle => 'Singleton',
326 name => 'class_config',
329 my $app = $s->param('application_name');
331 # Container might be called outside Catalyst context
332 return {} unless Class::MOP::is_class_loaded($app);
334 # config might not have been defined
335 return $app->config || {};
337 dependencies => [ depends_on('application_name') ],
341 sub build_global_config_service {
344 return Bread::Board::BlockInjection->new(
345 lifecycle => 'Singleton',
346 name => 'global_config',
350 return Config::Any->load_files({
351 files => $s->param('global_files'),
352 filter => \&_fix_syntax,
354 driver_args => $s->param('driver'),
357 dependencies => [ depends_on('global_files') ],
361 sub build_local_config_service {
364 return Bread::Board::BlockInjection->new(
365 lifecycle => 'Singleton',
366 name => 'local_config',
370 return Config::Any->load_files({
371 files => $s->param('local_files'),
372 filter => \&_fix_syntax,
374 driver_args => $s->param('driver'),
377 dependencies => [ depends_on('local_files') ],
381 sub build_config_path_service {
384 return Bread::Board::BlockInjection->new(
385 lifecycle => 'Singleton',
386 name => 'config_path',
390 my $path = $s->param('path');
391 my $prefix = $s->param('prefix');
393 my ( $extension ) = ( $path =~ m{\.(.{1,4})$} );
396 $path =~ s{[\/\\]$}{};
400 return [ $path, $extension ];
402 dependencies => [ depends_on('prefix'), depends_on('path') ],
406 sub build_config_local_suffix_service {
409 return Bread::Board::BlockInjection->new(
410 lifecycle => 'Singleton',
411 name => 'config_local_suffix',
414 my $suffix = Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG_LOCAL_SUFFIX' ) || $self->config_local_suffix;
418 dependencies => [ depends_on('application_name') ],
422 sub build_locate_components_service {
425 return Bread::Board::BlockInjection->new(
426 lifecycle => 'Singleton',
427 name => 'locate_components',
430 my $class = $s->param('application_name');
431 my $config = $s->param('config')->{ setup_components };
433 Catalyst::Exception->throw(
434 qq{You are using search_extra config option. That option is\n} .
435 qq{deprecated, please refer to the documentation for\n} .
436 qq{other ways of achieving the same results.\n}
437 ) if delete $config->{ search_extra };
439 my @paths = qw( ::Controller ::C ::Model ::M ::View ::V );
441 my $locator = Module::Pluggable::Object->new(
442 search_path => [ map { s/^(?=::)/$class/; $_; } @paths ],
446 return [ $locator->plugins ];
448 dependencies => [ depends_on('application_name'), depends_on('config') ],
452 sub setup_components {
454 warn("Setting up default components");
455 my $class = $self->resolve( service => 'application_name' );
456 my @comps = @{ $self->resolve( service => 'locate_components' ) };
457 my %comps = map { $_ => 1 } @comps;
458 my $deprecatedcatalyst_component_names = 0;
460 for my $component ( @comps ) {
462 # We pass ignore_loaded here so that overlay files for (e.g.)
463 # Model::DBI::Schema sub-classes are loaded - if it's in @comps
464 # we know M::P::O found a file on disk so this is safe
466 Catalyst::Utils::ensure_class_loaded( $component, { ignore_loaded => 1 } );
469 for my $component (@comps) {
470 $self->add_component( $component );
471 # FIXME - $instance->expand_modules() is broken
472 my @expanded_components = $self->expand_component_module( $component );
475 !$deprecatedcatalyst_component_names &&
476 ($deprecatedcatalyst_component_names = $component =~ m/::[CMV]::/) ||
477 ($deprecatedcatalyst_component_names = grep { /::[CMV]::/ } @expanded_components)
479 # FIXME - should I be calling warn here?
480 # Maybe it's time to remove it, or become fatal
481 $class->log->warn(qq{Your application is using the deprecated ::[MVC]:: type naming scheme.\n}.
482 qq{Please switch your class names to ::Model::, ::View:: and ::Controller: as appropriate.\n}
486 for my $component (@expanded_components) {
487 $self->add_component( $component )
488 unless $comps{$component};
497 prefix => $_ eq 'Component' ? '' : $_ . '::',
498 values => delete $config->{ lc $_ } || delete $config->{ $_ }
500 grep { ref $config->{ lc $_ } || ref $config->{ $_ } }
501 qw( Component Model M View V Controller C Plugin )
504 foreach my $comp ( @components ) {
505 my $prefix = $comp->{ prefix };
506 foreach my $element ( keys %{ $comp->{ values } } ) {
507 $config->{ "$prefix$element" } = $comp->{ values }->{ $element };
512 sub _config_substitutions {
513 my ( $self, $name, $subs, $arg ) = @_;
515 $subs->{ HOME } ||= sub { shift->path_to( '' ); };
519 if (! defined($ENV{$v})) {
520 Catalyst::Exception->throw( message =>
521 "Missing environment variable: $v" );
527 $subs->{ path_to } ||= sub { shift->path_to( @_ ); };
528 $subs->{ literal } ||= sub { return $_[ 1 ]; };
529 my $subsre = join( '|', keys %$subs );
531 $arg =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $name, $2 ? split( /,/, $2 ) : () ) }eg;
535 sub get_component_from_sub_container {
536 my ( $self, $sub_container_name, $name, $c, @args ) = @_;
538 my $sub_container = $self->get_sub_container( $sub_container_name );
541 my $default = $sub_container->default_component;
543 return $sub_container->get_component( $default, $c, @args )
544 if $default && $sub_container->has_service( $default );
546 # FIXME - should I be calling $c->log->warn here?
547 # this is never a controller, so this is safe
548 $c->log->warn( "Calling \$c->$sub_container_name() is not supported unless you specify one of:" );
549 $c->log->warn( "* \$c->config(default_$sub_container_name => 'the name of the default $sub_container_name to use')" );
550 $c->log->warn( "* \$c->stash->{current_$sub_container_name} # the name of the view to use for this request" );
551 $c->log->warn( "* \$c->stash->{current_${sub_container_name}_instance} # the instance of the $sub_container_name to use for this request" );
556 return $sub_container->get_component_regexp( $name, $c, @args )
559 return $sub_container->get_component( $name, $c, @args )
560 if $sub_container->has_service( $name );
563 "Attempted to use $sub_container_name '$name', " .
564 "but it does not exist"
571 my ( $self, $component, @args ) = @_;
572 my ( $type, $name ) = _get_component_type_name($component);
575 return $self->get_component_from_sub_container(
579 my $query = ref $component
584 for my $subcontainer_name (qw/model view controller/) {
585 my $subcontainer = $self->get_sub_container( $subcontainer_name );
586 my @components = $subcontainer->get_service_list;
587 @result = grep { m{$component} } @components;
589 return map { $subcontainer->get_component( $_, @args ) } @result
593 # one last search for things like $c->comp(qr/::M::/)
594 @result = $self->_find_component_regexp(
596 ) if !@result and ref $component;
598 # it expects an empty list on failed searches
602 sub _find_component_regexp {
603 my ( $self, $component, $ctx, @args ) = @_;
606 my @components = grep { m{$component} } keys %{ $self->get_all_components($ctx) };
609 my ($type, $name) = _get_component_type_name($_);
611 push @result, $self->get_component_from_sub_container(
612 $type, $name, $ctx, @args
619 sub get_all_components {
620 my ($self, $class) = @_;
623 # FIXME - if we're getting from these containers, we need to either:
624 # - pass 'ctx' and 'accept_context_args' OR
625 # - make these params optional
626 foreach my $type (qw/model view controller /) {
627 my $container = $self->get_sub_container($type);
629 for my $component ($container->get_service_list) {
630 my $comp_service = $container->get_service($component);
632 $components{$comp_service->catalyst_component_name} = $comp_service->get(ctx => $class);
636 return lock_hash %components;
640 my ( $self, $component ) = @_;
641 my ( $type, $name ) = _get_component_type_name($component);
645 # The 'component' sub-container will create the object, and store it's
646 # instance, which, by default, will live throughout the application.
647 # The model/view/controller sub-containers only reference the instance
648 # held in the aforementioned sub-container, and execute the ACCEPT_CONTEXT
649 # sub every time they are called, when it exists.
650 my $instance_container = $self->get_sub_container('component');
651 my $accept_context_container = $self->get_sub_container($type);
653 # Custom containers might have added the service already
654 # We don't want to override that
655 return if $accept_context_container->has_service( $name );
657 my $component_service_name = "${type}_${name}";
659 $instance_container->add_service(
660 Catalyst::IOC::ConstructorInjection->new(
661 name => $component_service_name,
662 catalyst_component_name => $component,
664 lifecycle => 'Singleton',
666 depends_on( '/application_name' ),
671 $accept_context_container->add_service(
672 Catalyst::IOC::BlockInjection->new(
674 catalyst_component_name => $component,
676 depends_on( "/component/$component_service_name" ),
678 block => sub { shift->param($component_service_name) },
683 # FIXME: should this sub exist?
684 # should it be moved to Catalyst::Utils,
685 # or replaced by something already existing there?
686 sub _get_component_type_name {
687 my ( $component ) = @_;
690 while ( !$result and (my $index = index $component, '::') > 0 ) {
691 my $type = lc substr $component, 0, $index;
692 $component = substr $component, $index + 2;
693 $result = first { $type eq $_ or $type eq substr($_, 0, 1) }
694 qw{ model view controller };
697 return ($result, $component);
700 sub expand_component_module {
701 my ( $class, $module ) = @_;
702 return Devel::InnerPackage::list_packages( $module );
713 Catalyst::Container - IOC for Catalyst components
721 =head1 Building Containers
723 =head2 build_component_subcontainer
725 Container that stores all components, i.e. all models, views and controllers
726 together. Each service is an instance of the actual component, and by default
727 it lives while the application is running. Retrieving components from this
728 subcontainer will instantiate the component, if it hasn't been instantiated
729 already, but will not execute ACCEPT_CONTEXT.
731 =head2 build_model_subcontainer
733 Container that stores references for all models that are inside the components
734 subcontainer. Retrieving a model triggers ACCEPT_CONTEXT, if it exists.
736 =head2 build_view_subcontainer
738 Same as L<build_model_subcontainer>, but for views.
740 =head2 build_controller_subcontainer
742 Same as L<build_model_subcontainer>, but for controllers.
744 =head1 Building Services
746 =head2 build_application_name_service
748 Name of the application (such as MyApp).
750 =head2 build_driver_service
752 Config options passed directly to the driver being used.
754 =head2 build_file_service
758 =head2 build_substitutions_service
760 This method substitutes macros found with calls to a function. There are a
761 number of default macros:
765 =item * C<__HOME__> - replaced with C<$c-E<gt>path_to('')>
767 =item * C<__ENV(foo)__> - replaced with the value of C<$ENV{foo}>
769 =item * C<__path_to(foo/bar)__> - replaced with C<$c-E<gt>path_to('foo/bar')>
771 =item * C<__literal(__FOO__)__> - leaves __FOO__ alone (allows you to use
772 C<__DATA__> as a config value, for example)
776 The parameter list is split on comma (C<,>). You can override this method to
777 do your own string munging, or you can define your own macros in
778 C<< <MyApp->config( 'Plugin::ConfigLoader' => { substitutions => { ... } } ) >>.
781 MyApp->config( 'Plugin::ConfigLoader' => {
783 baz => sub { my $c = shift; qux( @_ ); },
787 The above will respond to C<__baz(x,y)__> in config strings.
789 =head2 build_extensions_service
791 Config::Any's available config file extensions (e.g. xml, json, pl, etc).
793 =head2 build_prefix_service
795 The prefix, based on the application name, that will be used to lookup the
796 config files (which will be in the format $prefix.$extension). If the app is
797 MyApp::Foo, the prefix will be myapp_foo.
799 =head2 build_path_service
801 The path to the config file (or environment variable, if defined).
803 =head2 build_config_service
805 The resulting configuration for the application, after it has successfully
806 been loaded, and all substitutions have been made.
808 =head2 build_raw_config_service
810 The merge of local_config and global_config hashes, before substitutions.
812 =head2 build_global_files_service
814 Gets all files for config that don't have the local_suffix, such as myapp.conf.
816 =head2 build_local_files_service
818 Gets all files for config that have the local_suffix, such as myapp_local.conf.
820 =head2 build_global_config_service
822 Reads config from global_files.
824 =head2 build_local_config_service
826 Reads config from local_files.
828 =head2 build_class_config_service
830 Reads config set from the application's class attribute config,
831 i.e. MyApp->config( name => 'MyApp', ... )
833 =head2 build_config_path_service
835 Splits the path to the config file, and returns on array ref containing
836 the path to the config file minus the extension in the first position,
837 and the extension in the second.
839 =head2 build_config_local_suffix_service
841 Determines the suffix of files used to override the main config. By default
842 this value is C<local>, which will load C<myapp_local.conf>. The suffix can
843 be specified in the following order of preference:
847 =item * C<$ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }>
849 =item * C<$ENV{ CATALYST_CONFIG_LOCAL_SUFFIX }>
853 The first one of these values found replaces the default of C<local> in the
854 name of the local config file to be loaded.
856 For example, if C< $ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }> is set to C<testing>,
857 ConfigLoader will try and load C<myapp_testing.conf> instead of
860 =head2 build_locate_components_service
862 This method is meant to provide a list of component modules that should be
863 setup for the application. By default, it will use L<Module::Pluggable>.
865 Specify a C<setup_components> config option to pass additional options directly
866 to L<Module::Pluggable>.
870 =head2 get_component_from_sub_container($sub_container, $name, $c, @args)
872 Looks for components in a given subcontainer (such as controller, model or
873 view), and returns the searched component. If $name is undef, it returns the
874 default component (such as default_view, if $sub_container is 'view'). If
875 $name is a regexp, it returns an array of matching components. Otherwise, it
876 looks for the component with name $name.
878 =head2 get_all_components
880 Fetches all the components, in each of the sub_containers model, view and
881 controller, and returns a readonly hash. The keys are the class names, and
882 the values are the blessed objects. This is what is returned by $c->components.
886 Adds a component to the appropriate subcontainer. The subcontainer is guessed
887 by the component name given.
889 =head2 find_component
891 Searches for components in all containers. If $component is the full class
892 name, the subcontainer is guessed, and it gets the searched component in there.
893 Otherwise, it looks for a component with that name in all subcontainers. If
894 $component is a regexp it calls _find_component_regexp and matches all
895 components against that regexp.
897 =head2 expand_component_module
899 Components found by C<locate_components> will be passed to this method, which
900 is expected to return a list of component (package) names to be set up.
902 =head2 setup_components
906 Catalyst Contributors, see Catalyst.pm
910 This library is free software. You can redistribute it and/or modify it under
911 the same terms as Perl itself.