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 Scalar::Util qw/refaddr/;
13 use Catalyst::IOC::BlockInjection;
14 use Catalyst::IOC::ConstructorInjection;
15 use Module::Pluggable::Object ();
16 use namespace::autoclean;
18 extends 'Bread::Board::Container';
20 has config_local_suffix => (
29 default => sub { +{} },
38 has substitutions => (
41 default => sub { +{} },
44 has application_name => (
50 has sub_container_class => (
54 default => 'Catalyst::IOC::SubContainer',
56 new_sub_container => 'new',
61 my ( $self, $params ) = @_;
64 $self->${\"build_${_}_service"}
85 my $config = $self->resolve( service => 'config' );
87 # don't force default_component to be undef if the config wasn't set
88 my @default_view = $config->{default_view}
89 ? ( default_component => $config->{default_view} )
92 my @default_model = $config->{default_model}
93 ? ( default_component => $config->{default_model} )
97 $self->add_sub_container(
98 $self->build_component_subcontainer
101 $self->add_sub_container(
102 $self->build_controller_subcontainer
105 $self->add_sub_container(
106 $self->build_view_subcontainer( @default_view )
109 $self->add_sub_container(
110 $self->build_model_subcontainer( @default_model )
116 my $class = ref $self;
117 ${ $class . '::customise_container' }->($self)
118 if ${ $class . '::customise_container' };
122 sub build_model_subcontainer {
125 return $self->new_sub_container( @_,
130 sub build_view_subcontainer {
133 return $self->new_sub_container( @_,
138 sub build_controller_subcontainer {
141 return $self->new_sub_container(
142 name => 'controller',
146 sub build_component_subcontainer {
149 return Bread::Board::Container->new(
154 sub build_home_service {
157 return Bread::Board::BlockInjection->new(
158 lifecycle => 'Singleton',
162 my $class = $self->param('application_name');
165 if ( my $env = Catalyst::Utils::env_value( $class, 'HOME' ) ) {
169 $home ||= Catalyst::Utils::home($class);
173 dependencies => [ depends_on('application_name') ],
177 # FIXME: very ambiguous - maybe root_dir?
178 sub build_root_service {
181 return Bread::Board::BlockInjection->new(
182 lifecycle => 'Singleton',
187 return Path::Class::Dir->new( $self->param('home') )->subdir('root');
189 dependencies => [ depends_on('home') ],
193 sub build_application_name_service {
196 return Bread::Board::Literal->new( name => 'application_name', value => $self->application_name );
199 sub build_driver_service {
202 return Bread::Board::Literal->new( name => 'driver', value => $self->driver );
205 sub build_file_service {
208 return Bread::Board::Literal->new( name => 'file', value => $self->file );
211 sub build_substitutions_service {
214 return Bread::Board::Literal->new( name => 'substitutions', value => $self->substitutions );
217 sub build_extensions_service {
220 return Bread::Board::BlockInjection->new(
221 lifecycle => 'Singleton',
222 name => 'extensions',
224 return \@{Config::Any->extensions};
229 sub build_prefix_service {
232 return Bread::Board::BlockInjection->new(
233 lifecycle => 'Singleton',
236 return Catalyst::Utils::appprefix( shift->param('application_name') );
238 dependencies => [ depends_on('application_name') ],
242 sub build_path_service {
245 return Bread::Board::BlockInjection->new(
246 lifecycle => 'Singleton',
251 return Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG' )
253 || $s->param('application_name')->path_to( $s->param('prefix') );
255 dependencies => [ depends_on('file'), depends_on('application_name'), depends_on('prefix') ],
259 sub build_config_service {
262 return Bread::Board::BlockInjection->new(
263 lifecycle => 'Singleton',
268 my $v = Data::Visitor::Callback->new(
270 return unless defined $_;
271 return $self->_config_substitutions( $s->param('application_name'), $s->param('substitutions'), $_ );
275 $v->visit( $s->param('raw_config') );
277 dependencies => [ depends_on('application_name'), depends_on('raw_config'), depends_on('substitutions') ],
281 sub build_raw_config_service {
284 return Bread::Board::BlockInjection->new(
285 lifecycle => 'Singleton',
286 name => 'raw_config',
290 my @global = @{$s->param('global_config')};
291 my @locals = @{$s->param('local_config')};
293 my $config = $s->param('class_config');
295 for my $cfg (@global, @locals) {
297 $config = Catalyst::Utils::merge_hashes( $config, $cfg->{$_} );
303 dependencies => [ depends_on('global_config'), depends_on('local_config'), depends_on('class_config') ],
307 sub build_global_files_service {
310 return Bread::Board::BlockInjection->new(
311 lifecycle => 'Singleton',
312 name => 'global_files',
316 my ( $path, $extension ) = @{$s->param('config_path')};
318 my @extensions = @{$s->param('extensions')};
322 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
325 @files = map { "$path.$_" } @extensions;
329 dependencies => [ depends_on('extensions'), depends_on('config_path') ],
333 sub build_local_files_service {
336 return Bread::Board::BlockInjection->new(
337 lifecycle => 'Singleton',
338 name => 'local_files',
342 my ( $path, $extension ) = @{$s->param('config_path')};
343 my $suffix = $s->param('config_local_suffix');
345 my @extensions = @{$s->param('extensions')};
349 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
350 $path =~ s{\.$extension}{_$suffix.$extension};
353 @files = map { "${path}_${suffix}.$_" } @extensions;
357 dependencies => [ depends_on('extensions'), depends_on('config_path'), depends_on('config_local_suffix') ],
361 sub build_class_config_service {
364 return Bread::Board::BlockInjection->new(
365 lifecycle => 'Singleton',
366 name => 'class_config',
369 my $app = $s->param('application_name');
371 # Container might be called outside Catalyst context
372 return {} unless Class::MOP::is_class_loaded($app);
374 # config might not have been defined
375 return $app->config || {};
377 dependencies => [ depends_on('application_name') ],
381 sub build_global_config_service {
384 return Bread::Board::BlockInjection->new(
385 lifecycle => 'Singleton',
386 name => 'global_config',
390 return Config::Any->load_files({
391 files => $s->param('global_files'),
392 filter => \&_fix_syntax,
394 driver_args => $s->param('driver'),
397 dependencies => [ depends_on('global_files') ],
401 sub build_local_config_service {
404 return Bread::Board::BlockInjection->new(
405 lifecycle => 'Singleton',
406 name => 'local_config',
410 return Config::Any->load_files({
411 files => $s->param('local_files'),
412 filter => \&_fix_syntax,
414 driver_args => $s->param('driver'),
417 dependencies => [ depends_on('local_files') ],
421 sub build_config_path_service {
424 return Bread::Board::BlockInjection->new(
425 lifecycle => 'Singleton',
426 name => 'config_path',
430 my $path = $s->param('path');
431 my $prefix = $s->param('prefix');
433 my ( $extension ) = ( $path =~ m{\.(.{1,4})$} );
436 $path =~ s{[\/\\]$}{};
440 return [ $path, $extension ];
442 dependencies => [ depends_on('prefix'), depends_on('path') ],
446 sub build_config_local_suffix_service {
449 return Bread::Board::BlockInjection->new(
450 lifecycle => 'Singleton',
451 name => 'config_local_suffix',
454 my $suffix = Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG_LOCAL_SUFFIX' ) || $self->config_local_suffix;
458 dependencies => [ depends_on('application_name') ],
462 sub build_locate_components_service {
465 return Bread::Board::BlockInjection->new(
466 lifecycle => 'Singleton',
467 name => 'locate_components',
470 my $class = $s->param('application_name');
471 my $config = $s->param('config')->{ setup_components };
473 Catalyst::Exception->throw(
474 qq{You are using search_extra config option. That option is\n} .
475 qq{deprecated, please refer to the documentation for\n} .
476 qq{other ways of achieving the same results.\n}
477 ) if delete $config->{ search_extra };
479 my @paths = qw( ::Controller ::C ::Model ::M ::View ::V );
481 my $locator = Module::Pluggable::Object->new(
482 search_path => [ map { s/^(?=::)/$class/; $_; } @paths ],
486 return [ $locator->plugins ];
488 dependencies => [ depends_on('application_name'), depends_on('config') ],
492 sub setup_components {
494 my $class = $self->resolve( service => 'application_name' );
495 my @comps = @{ $self->resolve( service => 'locate_components' ) };
496 my %comps = map { $_ => 1 } @comps;
497 my $deprecatedcatalyst_component_names = 0;
499 my $app_locate_components_addr = refaddr(
500 $class->can('locate_components')
502 my $cat_locate_components_addr = refaddr(
503 Catalyst->can('locate_components')
506 if ($app_locate_components_addr != $cat_locate_components_addr) {
507 # FIXME - why not just say: @comps = $class->locate_components() ?
508 $class->log->warn(qq{You have overridden locate_components. That } .
509 qq{no longer works. Please refer to the documentation to achieve } .
510 qq{similar results.\n}
514 for my $component ( @comps ) {
516 # We pass ignore_loaded here so that overlay files for (e.g.)
517 # Model::DBI::Schema sub-classes are loaded - if it's in @comps
518 # we know M::P::O found a file on disk so this is safe
520 Catalyst::Utils::ensure_class_loaded( $component, { ignore_loaded => 1 } );
523 for my $component (@comps) {
524 $self->add_component( $component );
525 # FIXME - $instance->expand_modules() is broken
526 my @expanded_components = $self->expand_component_module( $component );
529 !$deprecatedcatalyst_component_names &&
530 ($deprecatedcatalyst_component_names = $component =~ m/::[CMV]::/) ||
531 ($deprecatedcatalyst_component_names = grep { /::[CMV]::/ } @expanded_components)
533 # FIXME - should I be calling warn here?
534 # Maybe it's time to remove it, or become fatal
535 $class->log->warn(qq{Your application is using the deprecated ::[MVC]:: type naming scheme.\n}.
536 qq{Please switch your class names to ::Model::, ::View:: and ::Controller: as appropriate.\n}
540 for my $component (@expanded_components) {
541 $self->add_component( $component )
542 unless $comps{$component};
551 prefix => $_ eq 'Component' ? '' : $_ . '::',
552 values => delete $config->{ lc $_ } || delete $config->{ $_ }
554 grep { ref $config->{ lc $_ } || ref $config->{ $_ } }
555 qw( Component Model M View V Controller C Plugin )
558 foreach my $comp ( @components ) {
559 my $prefix = $comp->{ prefix };
560 foreach my $element ( keys %{ $comp->{ values } } ) {
561 $config->{ "$prefix$element" } = $comp->{ values }->{ $element };
566 sub _config_substitutions {
567 my ( $self, $name, $subs, $arg ) = @_;
569 $subs->{ HOME } ||= sub { shift->path_to( '' ); };
573 if (! defined($ENV{$v})) {
574 Catalyst::Exception->throw( message =>
575 "Missing environment variable: $v" );
581 $subs->{ path_to } ||= sub { shift->path_to( @_ ); };
582 $subs->{ literal } ||= sub { return $_[ 1 ]; };
583 my $subsre = join( '|', keys %$subs );
585 $arg =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $name, $2 ? split( /,/, $2 ) : () ) }eg;
589 sub get_component_from_sub_container {
590 my ( $self, $sub_container_name, $name, $c, @args ) = @_;
592 my $sub_container = $self->get_sub_container( $sub_container_name );
595 my $default = $sub_container->default_component;
597 return $sub_container->get_component( $default, $c, @args )
598 if $default && $sub_container->has_service( $default );
600 # FIXME - should I be calling $c->log->warn here?
601 # this is never a controller, so this is safe
602 $c->log->warn( "Calling \$c->$sub_container_name() is not supported unless you specify one of:" );
603 $c->log->warn( "* \$c->config(default_$sub_container_name => 'the name of the default $sub_container_name to use')" );
604 $c->log->warn( "* \$c->stash->{current_$sub_container_name} # the name of the view to use for this request" );
605 $c->log->warn( "* \$c->stash->{current_${sub_container_name}_instance} # the instance of the $sub_container_name to use for this request" );
610 return $sub_container->get_component_regexp( $name, $c, @args )
613 return $sub_container->get_component( $name, $c, @args )
614 if $sub_container->has_service( $name );
617 "Attempted to use $sub_container_name '$name', " .
618 "but it does not exist"
625 my ( $self, $component, @args ) = @_;
626 my ( $type, $name ) = _get_component_type_name($component);
629 return $self->get_component_from_sub_container(
633 my $query = ref $component
638 for my $subcontainer_name (qw/model view controller/) {
639 my $subcontainer = $self->get_sub_container( $subcontainer_name );
640 my @components = $subcontainer->get_service_list;
641 @result = grep { m{$component} } @components;
643 return map { $subcontainer->get_component( $_, @args ) } @result
647 # one last search for things like $c->comp(qr/::M::/)
648 @result = $self->_find_component_regexp(
650 ) if !@result and ref $component;
652 # it expects an empty list on failed searches
656 sub _find_component_regexp {
657 my ( $self, $component, $ctx, @args ) = @_;
660 my @components = grep { m{$component} } keys %{ $self->get_all_components($ctx) };
663 my ($type, $name) = _get_component_type_name($_);
665 push @result, $self->get_component_from_sub_container(
666 $type, $name, $ctx, @args
673 sub get_all_components {
674 my ($self, $class) = @_;
677 # FIXME - if we're getting from these containers, we need to either:
678 # - pass 'ctx' and 'accept_context_args' OR
679 # - make these params optional
680 # big problem when setting up the dispatcher - this method is called
681 # as $container->get_all_components('MyApp'). What to do with Request
683 foreach my $type (qw/model view controller /) {
684 my $container = $self->get_sub_container($type);
686 for my $component ($container->get_service_list) {
687 my $comp_service = $container->get_service($component);
689 $components{$comp_service->catalyst_component_name} = $comp_service->get(ctx => $class);
693 return lock_hash %components;
697 my ( $self, $component ) = @_;
698 my ( $type, $name ) = _get_component_type_name($component);
702 # The 'component' sub-container will create the object, and store it's
703 # instance, which, by default, will live throughout the application.
704 # The model/view/controller sub-containers only reference the instance
705 # held in the aforementioned sub-container, and execute the ACCEPT_CONTEXT
706 # sub every time they are called, when it exists.
707 my $instance_container = $self->get_sub_container('component');
708 my $accept_context_container = $self->get_sub_container($type);
710 # Custom containers might have added the service already
711 # We don't want to override that
712 return if $accept_context_container->has_service( $name );
714 my $component_service_name = "${type}_${name}";
716 $instance_container->add_service(
717 Catalyst::IOC::ConstructorInjection->new(
718 name => $component_service_name,
719 catalyst_component_name => $component,
721 lifecycle => 'Singleton',
723 depends_on( '/application_name' ),
727 # XXX - FIXME - We have to explicitly build the service here,
728 # causing the COMPONENT method to be called early here, as otherwise
729 # if the component method defines other classes (e.g. the
730 # ACCEPT_CONTEXT injection Model::DBIC::Schema does)
731 # then they won't be found by Devel::InnerPackage
732 # see also t/aggregate/unit_core_component_loading.t
733 $instance_container->get_service($component_service_name)->get;
735 $accept_context_container->add_service(
736 Catalyst::IOC::BlockInjection->new(
738 catalyst_component_name => $component,
740 depends_on( "/component/$component_service_name" ),
742 block => sub { shift->param($component_service_name) },
747 # FIXME: should this sub exist?
748 # should it be moved to Catalyst::Utils,
749 # or replaced by something already existing there?
750 sub _get_component_type_name {
751 my ( $component ) = @_;
754 while ( !$result and (my $index = index $component, '::') > 0 ) {
755 my $type = lc substr $component, 0, $index;
756 $component = substr $component, $index + 2;
757 $result = first { $type eq $_ or $type eq substr($_, 0, 1) }
758 qw{ model view controller };
761 return ($result, $component);
764 sub expand_component_module {
765 my ( $class, $module ) = @_;
766 return Devel::InnerPackage::list_packages( $module );
777 Catalyst::Container - IOC for Catalyst components
785 =head1 Methods for Building Containers
787 =head2 build_component_subcontainer
789 Container that stores all components, i.e. all models, views and controllers
790 together. Each service is an instance of the actual component, and by default
791 it lives while the application is running. Retrieving components from this
792 sub-container will instantiate the component, if it hasn't been instantiated
793 already, but will not execute ACCEPT_CONTEXT.
795 =head2 build_model_subcontainer
797 Container that stores references for all models that are inside the components
798 sub-container. Retrieving a model triggers ACCEPT_CONTEXT, if it exists.
800 =head2 build_view_subcontainer
802 Same as L<build_model_subcontainer>, but for views.
804 =head2 build_controller_subcontainer
806 Same as L<build_model_subcontainer>, but for controllers.
808 =head1 Methods for Building Services
810 =head2 build_application_name_service
812 Name of the application (such as MyApp).
814 =head2 build_driver_service
816 Config options passed directly to the driver being used.
818 =head2 build_file_service
822 =head2 build_substitutions_service
824 This method substitutes macros found with calls to a function. There are a
825 number of default macros:
829 =item * C<__HOME__> - replaced with C<$c-E<gt>path_to('')>
831 =item * C<__ENV(foo)__> - replaced with the value of C<$ENV{foo}>
833 =item * C<__path_to(foo/bar)__> - replaced with C<$c-E<gt>path_to('foo/bar')>
835 =item * C<__literal(__FOO__)__> - leaves __FOO__ alone (allows you to use
836 C<__DATA__> as a config value, for example)
840 The parameter list is split on comma (C<,>). You can override this method to
841 do your own string munging, or you can define your own macros in
842 C<< <MyApp->config( 'Plugin::ConfigLoader' => { substitutions => { ... } } ) >>.
845 MyApp->config( 'Plugin::ConfigLoader' => {
847 baz => sub { my $c = shift; qux( @_ ); },
851 The above will respond to C<__baz(x,y)__> in config strings.
853 =head2 build_extensions_service
855 Config::Any's available config file extensions (e.g. xml, json, pl, etc).
857 =head2 build_prefix_service
859 The prefix, based on the application name, that will be used to look-up the
860 config files (which will be in the format $prefix.$extension). If the app is
861 MyApp::Foo, the prefix will be myapp_foo.
863 =head2 build_path_service
865 The path to the config file (or environment variable, if defined).
867 =head2 build_config_service
869 The resulting configuration for the application, after it has successfully
870 been loaded, and all substitutions have been made.
872 =head2 build_raw_config_service
874 The merge of local_config and global_config hashes, before substitutions.
876 =head2 build_global_files_service
878 Gets all files for config that don't have the local_suffix, such as myapp.conf.
880 =head2 build_local_files_service
882 Gets all files for config that have the local_suffix, such as myapp_local.conf.
884 =head2 build_global_config_service
886 Reads config from global_files.
888 =head2 build_local_config_service
890 Reads config from local_files.
892 =head2 build_class_config_service
894 Reads config set from the application's class attribute config,
895 i.e. MyApp->config( name => 'MyApp', ... )
897 =head2 build_config_path_service
899 Splits the path to the config file, and returns on array ref containing
900 the path to the config file minus the extension in the first position,
901 and the extension in the second.
903 =head2 build_config_local_suffix_service
905 Determines the suffix of files used to override the main config. By default
906 this value is C<local>, which will load C<myapp_local.conf>. The suffix can
907 be specified in the following order of preference:
911 =item * C<$ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }>
913 =item * C<$ENV{ CATALYST_CONFIG_LOCAL_SUFFIX }>
917 The first one of these values found replaces the default of C<local> in the
918 name of the local config file to be loaded.
920 For example, if C< $ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }> is set to C<testing>,
921 ConfigLoader will try and load C<myapp_testing.conf> instead of
924 =head2 build_locate_components_service
926 This method is meant to provide a list of component modules that should be
927 setup for the application. By default, it will use L<Module::Pluggable>.
929 Specify a C<setup_components> config option to pass additional options directly
930 to L<Module::Pluggable>.
934 =head2 get_component_from_sub_container($sub_container, $name, $c, @args)
936 Looks for components in a given sub-container (such as controller, model or
937 view), and returns the searched component. If $name is undef, it returns the
938 default component (such as default_view, if $sub_container is 'view'). If
939 $name is a regexp, it returns an array of matching components. Otherwise, it
940 looks for the component with name $name.
942 =head2 get_all_components
944 Fetches all the components, in each of the sub_containers model, view and
945 controller, and returns a read-only hash. The keys are the class names, and
946 the values are the blessed objects. This is what is returned by $c->components.
950 Adds a component to the appropriate sub-container. The sub-container is guessed
951 by the component name given.
953 =head2 find_component
955 Searches for components in all containers. If $component is the full class
956 name, the sub-container is guessed, and it gets the searched component in there.
957 Otherwise, it looks for a component with that name in all sub-containers. If
958 $component is a regexp it calls _find_component_regexp and matches all
959 components against that regexp.
961 =head2 expand_component_module
963 Components found by C<locate_components> will be passed to this method, which
964 is expected to return a list of component (package) names to be set up.
966 =head2 setup_components
968 Uses locate_components service to list the components, and adds them to the
969 appropriate sub-containers, using add_component().
973 Catalyst Contributors, see Catalyst.pm
977 This library is free software. You can redistribute it and/or modify it under
978 the same terms as Perl itself.