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 Catalyst::IOC::ConstructorInjection;
13 use Module::Pluggable::Object ();
14 use namespace::autoclean;
16 extends 'Bread::Board::Container';
18 has config_local_suffix => (
27 default => sub { +{} },
36 has substitutions => (
39 default => sub { +{} },
42 has application_name => (
48 has sub_container_class => (
52 default => 'Catalyst::IOC::SubContainer',
54 new_sub_container => 'new',
59 my ( $self, $params ) = @_;
62 $self->${\"build_${_}_service"}
83 my $config = $self->resolve( service => 'config' );
85 $self->add_sub_container(
86 $self->build_component_subcontainer
89 $self->add_sub_container(
90 $self->build_controller_subcontainer
93 $self->add_sub_container(
94 $self->build_view_subcontainer(
95 default_component => $config->{default_view},
99 $self->add_sub_container(
100 $self->build_model_subcontainer(
101 default_component => $config->{default_model},
106 sub build_model_subcontainer {
109 return $self->new_sub_container( @_,
114 sub build_view_subcontainer {
117 return $self->new_sub_container( @_,
122 sub build_controller_subcontainer {
125 return $self->new_sub_container(
126 name => 'controller',
130 sub build_component_subcontainer {
133 return Bread::Board::Container->new(
138 sub build_application_name_service {
141 return Bread::Board::Literal->new( name => 'application_name', value => $self->application_name );
144 sub build_driver_service {
147 return Bread::Board::Literal->new( name => 'driver', value => $self->driver );
150 sub build_file_service {
153 return Bread::Board::Literal->new( name => 'file', value => $self->file );
156 sub build_substitutions_service {
159 return Bread::Board::Literal->new( name => 'substitutions', value => $self->substitutions );
162 sub build_extensions_service {
165 return Bread::Board::BlockInjection->new(
166 lifecycle => 'Singleton',
167 name => 'extensions',
169 return \@{Config::Any->extensions};
174 sub build_prefix_service {
177 return Bread::Board::BlockInjection->new(
178 lifecycle => 'Singleton',
181 return Catalyst::Utils::appprefix( shift->param('application_name') );
183 dependencies => [ depends_on('application_name') ],
187 sub build_path_service {
190 return Bread::Board::BlockInjection->new(
191 lifecycle => 'Singleton',
196 return Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG' )
198 || $s->param('application_name')->path_to( $s->param('prefix') );
200 dependencies => [ depends_on('file'), depends_on('application_name'), depends_on('prefix') ],
204 sub build_config_service {
207 return Bread::Board::BlockInjection->new(
208 lifecycle => 'Singleton',
213 my $v = Data::Visitor::Callback->new(
215 return unless defined $_;
216 return $self->_config_substitutions( $s->param('application_name'), $s->param('substitutions'), $_ );
220 $v->visit( $s->param('raw_config') );
222 dependencies => [ depends_on('application_name'), depends_on('raw_config'), depends_on('substitutions') ],
226 sub build_raw_config_service {
229 return Bread::Board::BlockInjection->new(
230 lifecycle => 'Singleton',
231 name => 'raw_config',
235 my @global = @{$s->param('global_config')};
236 my @locals = @{$s->param('local_config')};
238 my $config = $s->param('class_config');
240 for my $cfg (@global, @locals) {
242 $config = Catalyst::Utils::merge_hashes( $config, $cfg->{$_} );
248 dependencies => [ depends_on('global_config'), depends_on('local_config'), depends_on('class_config') ],
252 sub build_global_files_service {
255 return Bread::Board::BlockInjection->new(
256 lifecycle => 'Singleton',
257 name => 'global_files',
261 my ( $path, $extension ) = @{$s->param('config_path')};
263 my @extensions = @{$s->param('extensions')};
267 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
270 @files = map { "$path.$_" } @extensions;
274 dependencies => [ depends_on('extensions'), depends_on('config_path') ],
278 sub build_local_files_service {
281 return Bread::Board::BlockInjection->new(
282 lifecycle => 'Singleton',
283 name => 'local_files',
287 my ( $path, $extension ) = @{$s->param('config_path')};
288 my $suffix = $s->param('config_local_suffix');
290 my @extensions = @{$s->param('extensions')};
294 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
295 $path =~ s{\.$extension}{_$suffix.$extension};
298 @files = map { "${path}_${suffix}.$_" } @extensions;
302 dependencies => [ depends_on('extensions'), depends_on('config_path'), depends_on('config_local_suffix') ],
306 sub build_class_config_service {
309 return Bread::Board::BlockInjection->new(
310 lifecycle => 'Singleton',
311 name => 'class_config',
314 my $app = $s->param('application_name');
316 # Container might be called outside Catalyst context
317 return {} unless Class::MOP::is_class_loaded($app);
319 # config might not have been defined
320 return $app->config || {};
322 dependencies => [ depends_on('application_name') ],
326 sub build_global_config_service {
329 return Bread::Board::BlockInjection->new(
330 lifecycle => 'Singleton',
331 name => 'global_config',
335 return Config::Any->load_files({
336 files => $s->param('global_files'),
337 filter => \&_fix_syntax,
339 driver_args => $s->param('driver'),
342 dependencies => [ depends_on('global_files') ],
346 sub build_local_config_service {
349 return Bread::Board::BlockInjection->new(
350 lifecycle => 'Singleton',
351 name => 'local_config',
355 return Config::Any->load_files({
356 files => $s->param('local_files'),
357 filter => \&_fix_syntax,
359 driver_args => $s->param('driver'),
362 dependencies => [ depends_on('local_files') ],
366 sub build_config_path_service {
369 return Bread::Board::BlockInjection->new(
370 lifecycle => 'Singleton',
371 name => 'config_path',
375 my $path = $s->param('path');
376 my $prefix = $s->param('prefix');
378 my ( $extension ) = ( $path =~ m{\.(.{1,4})$} );
381 $path =~ s{[\/\\]$}{};
385 return [ $path, $extension ];
387 dependencies => [ depends_on('prefix'), depends_on('path') ],
391 sub build_config_local_suffix_service {
394 return Bread::Board::BlockInjection->new(
395 lifecycle => 'Singleton',
396 name => 'config_local_suffix',
399 my $suffix = Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG_LOCAL_SUFFIX' ) || $self->config_local_suffix;
403 dependencies => [ depends_on('application_name') ],
407 sub build_locate_components_service {
410 return Bread::Board::BlockInjection->new(
411 lifecycle => 'Singleton',
412 name => 'locate_components',
415 my $class = $s->param('application_name');
416 my $config = $s->param('config')->{ setup_components };
418 Catalyst::Exception->throw(
419 qq{You are using search_extra config option. That option is\n} .
420 qq{deprecated, please refer to the documentation for\n} .
421 qq{other ways of achieving the same results.\n}
422 ) if delete $config->{ search_extra };
424 my @paths = qw( ::Controller ::C ::Model ::M ::View ::V );
426 my $locator = Module::Pluggable::Object->new(
427 search_path => [ map { s/^(?=::)/$class/; $_; } @paths ],
431 return [ $locator->plugins ];
433 dependencies => [ depends_on('application_name'), depends_on('config') ],
437 sub setup_components {
439 my $class = $self->resolve( service => 'application_name' );
440 my @comps = @{ $self->resolve( service => 'locate_components' ) };
441 my %comps = map { $_ => 1 } @comps;
442 my $deprecatedcatalyst_component_names = 0;
444 for my $component ( @comps ) {
446 # We pass ignore_loaded here so that overlay files for (e.g.)
447 # Model::DBI::Schema sub-classes are loaded - if it's in @comps
448 # we know M::P::O found a file on disk so this is safe
450 Catalyst::Utils::ensure_class_loaded( $component, { ignore_loaded => 1 } );
453 for my $component (@comps) {
454 $self->add_component( $component );
455 # FIXME - $instance->expand_modules() is broken
456 my @expanded_components = $self->expand_component_module( $component );
459 !$deprecatedcatalyst_component_names &&
460 ($deprecatedcatalyst_component_names = $component =~ m/::[CMV]::/) ||
461 ($deprecatedcatalyst_component_names = grep { /::[CMV]::/ } @expanded_components)
463 # FIXME - should I be calling warn here?
464 # Maybe it's time to remove it, or become fatal
465 $class->log->warn(qq{Your application is using the deprecated ::[MVC]:: type naming scheme.\n}.
466 qq{Please switch your class names to ::Model::, ::View:: and ::Controller: as appropriate.\n}
470 for my $component (@expanded_components) {
471 $self->add_component( $component )
472 unless $comps{$component};
481 prefix => $_ eq 'Component' ? '' : $_ . '::',
482 values => delete $config->{ lc $_ } || delete $config->{ $_ }
484 grep { ref $config->{ lc $_ } || ref $config->{ $_ } }
485 qw( Component Model M View V Controller C Plugin )
488 foreach my $comp ( @components ) {
489 my $prefix = $comp->{ prefix };
490 foreach my $element ( keys %{ $comp->{ values } } ) {
491 $config->{ "$prefix$element" } = $comp->{ values }->{ $element };
496 sub _config_substitutions {
497 my ( $self, $name, $subs, $arg ) = @_;
499 $subs->{ HOME } ||= sub { shift->path_to( '' ); };
503 if (! defined($ENV{$v})) {
504 Catalyst::Exception->throw( message =>
505 "Missing environment variable: $v" );
511 $subs->{ path_to } ||= sub { shift->path_to( @_ ); };
512 $subs->{ literal } ||= sub { return $_[ 1 ]; };
513 my $subsre = join( '|', keys %$subs );
515 $arg =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $name, $2 ? split( /,/, $2 ) : () ) }eg;
519 sub get_component_from_sub_container {
520 my ( $self, $sub_container_name, $name, $c, @args ) = @_;
522 my $sub_container = $self->get_sub_container( $sub_container_name );
525 my $default = $sub_container->default_component;
527 return $sub_container->get_component( $default, $c, @args )
528 if $default && $sub_container->has_service( $default );
530 # FIXME - should I be calling $c->log->warn here?
531 # this is never a controller, so this is safe
532 $c->log->warn( "Calling \$c->$sub_container_name() is not supported unless you specify one of:" );
533 $c->log->warn( "* \$c->config(default_$sub_container_name => 'the name of the default $sub_container_name to use')" );
534 $c->log->warn( "* \$c->stash->{current_$sub_container_name} # the name of the view to use for this request" );
535 $c->log->warn( "* \$c->stash->{current_${sub_container_name}_instance} # the instance of the $sub_container_name to use for this request" );
540 return $sub_container->get_component_regexp( $name, $c, @args )
543 return $sub_container->get_component( $name, $c, @args )
544 if $sub_container->has_service( $name );
547 "Attempted to use $sub_container_name '$name', " .
548 "but it does not exist"
555 my ( $self, $component, @args ) = @_;
556 my ( $type, $name ) = _get_component_type_name($component);
559 return $self->get_component_from_sub_container(
563 my $query = ref $component
568 for my $subcontainer_name (qw/model view controller/) {
569 my $subcontainer = $self->get_sub_container( $subcontainer_name );
570 my @components = $subcontainer->get_service_list;
571 @result = grep { m{$component} } @components;
573 return map { $subcontainer->get_component( $_, @args ) } @result
577 # one last search for things like $c->comp(qr/::M::/)
578 @result = $self->find_component_regexp(
580 ) if !@result and ref $component;
582 # it expects an empty list on failed searches
586 sub find_component_regexp {
587 my ( $self, $component, @args ) = @_;
590 my @components = grep { m{$component} } keys %{ $self->get_all_components };
593 my ($type, $name) = _get_component_type_name($_);
595 push @result, $self->get_component_from_sub_container(
603 sub get_all_components {
607 my $container = $self->get_sub_container('component');
609 for my $component ($container->get_service_list) {
610 my $comp = $container->resolve(
611 service => $component
613 my $comp_name = ref $comp || $comp;
614 $components{$comp_name} = $comp;
617 return lock_hash %components;
621 my ( $self, $component ) = @_;
622 my ( $type, $name ) = _get_component_type_name($component);
626 my $component_service_name = "${type}_${name}";
628 # The 'component' sub-container will create the object, and store it's
629 # instance, which, by default, will live throughout the application.
630 # The model/view/controller sub-containers only reference the instance
631 # held in the aforementioned sub-container, and execute the ACCEPT_CONTEXT
632 # sub every time they are called, when it exists.
633 my $instance_container = $self->get_sub_container('component');
634 my $accept_context_container = $self->get_sub_container($type);
636 $instance_container->add_service(
637 Catalyst::IOC::ConstructorInjection->new(
638 name => $component_service_name,
640 lifecycle => 'Singleton',
642 depends_on( '/application_name' ),
643 depends_on( '/config' ),
646 ) unless $instance_container->has_service( $component_service_name );
647 # ^ custom containers might have added the service already.
648 # we don't want to override that.
650 $accept_context_container->add_service(
651 Catalyst::IOC::BlockInjection->new(
654 depends_on( "/component/$component_service_name" ),
656 block => sub { shift->param($component_service_name) },
658 ) unless $accept_context_container->has_service( $name );
662 # FIXME: should this sub exist?
663 # should it be moved to Catalyst::Utils,
664 # or replaced by something already existing there?
665 sub _get_component_type_name {
666 my ( $component ) = @_;
668 my @parts = split /::/, $component;
670 while (my $type = shift @parts) {
671 return ('controller', join '::', @parts)
672 if $type =~ /^(c|controller)$/i;
674 return ('model', join '::', @parts)
675 if $type =~ /^(m|model)$/i;
677 return ('view', join '::', @parts)
678 if $type =~ /^(v|view)$/i;
681 return (undef, $component);
684 sub expand_component_module {
685 my ( $class, $module ) = @_;
686 return Devel::InnerPackage::list_packages( $module );
689 # copied from stevan's OX
690 sub flush_request_services {
692 my @services = $self->get_service_list;
694 foreach my $service (@services) {
695 my $injection = $self->get_service($service);
696 if ($injection->does('Catalyst::IOC::LifeCycle::Request')) {
697 $injection->flush_instance;
710 Catalyst::Container - IOC for Catalyst components
718 =head1 Building Containers
720 =head2 build_component_subcontainer
722 Container that stores all components, i.e. all models, views and controllers
723 together. Each service is an instance of the actual component, and by default
724 it lives while the application is running. Retrieving components from this
725 subcontainer will instantiate the component, if it hasn't been instantiated
726 already, but will not execute ACCEPT_CONTEXT.
728 =head2 build_model_subcontainer
730 Container that stores references for all models that are inside the components
731 subcontainer. Retrieving a model triggers ACCEPT_CONTEXT, if it exists.
733 =head2 build_view_subcontainer
735 Same as L<build_model_subcontainer>, but for views.
737 =head2 build_controller_subcontainer
739 Same as L<build_model_subcontainer>, but for controllers.
741 =head1 Building Services
743 =head2 build_application_name_service
745 Name of the application (such as MyApp).
747 =head2 build_driver_service
749 Config options passed directly to the driver being used.
751 =head2 build_file_service
755 =head2 build_substitutions_service
757 This method substitutes macros found with calls to a function. There are a
758 number of default macros:
762 =item * C<__HOME__> - replaced with C<$c-E<gt>path_to('')>
764 =item * C<__ENV(foo)__> - replaced with the value of C<$ENV{foo}>
766 =item * C<__path_to(foo/bar)__> - replaced with C<$c-E<gt>path_to('foo/bar')>
768 =item * C<__literal(__FOO__)__> - leaves __FOO__ alone (allows you to use
769 C<__DATA__> as a config value, for example)
773 The parameter list is split on comma (C<,>). You can override this method to
774 do your own string munging, or you can define your own macros in
775 C<< <MyApp->config( 'Plugin::ConfigLoader' => { substitutions => { ... } } ) >>.
778 MyApp->config( 'Plugin::ConfigLoader' => {
780 baz => sub { my $c = shift; qux( @_ ); },
784 The above will respond to C<__baz(x,y)__> in config strings.
786 =head2 build_extensions_service
788 Config::Any's available config file extensions (e.g. xml, json, pl, etc).
790 =head2 build_prefix_service
792 The prefix, based on the application name, that will be used to lookup the
793 config files (which will be in the format $prefix.$extension). If the app is
794 MyApp::Foo, the prefix will be myapp_foo.
796 =head2 build_path_service
798 The path to the config file (or environment variable, if defined).
800 =head2 build_config_service
802 The resulting configuration for the application, after it has successfully
803 been loaded, and all substitutions have been made.
805 =head2 build_raw_config_service
807 The merge of local_config and global_config hashes, before substitutions.
809 =head2 build_global_files_service
811 Gets all files for config that don't have the local_suffix, such as myapp.conf.
813 =head2 build_local_files_service
815 Gets all files for config that have the local_suffix, such as myapp_local.conf.
817 =head2 build_global_config_service
819 Reads config from global_files.
821 =head2 build_local_config_service
823 Reads config from local_files.
825 =head2 build_class_config_service
827 Reads config set from the application's class attribute config,
828 i.e. MyApp->config( name => 'MyApp', ... )
830 =head2 build_config_path_service
832 Splits the path to the config file, and returns on array ref containing
833 the path to the config file minus the extension in the first position,
834 and the extension in the second.
836 =head2 build_config_local_suffix_service
838 Determines the suffix of files used to override the main config. By default
839 this value is C<local>, which will load C<myapp_local.conf>. The suffix can
840 be specified in the following order of preference:
844 =item * C<$ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }>
846 =item * C<$ENV{ CATALYST_CONFIG_LOCAL_SUFFIX }>
850 The first one of these values found replaces the default of C<local> in the
851 name of the local config file to be loaded.
853 For example, if C< $ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }> is set to C<testing>,
854 ConfigLoader will try and load C<myapp_testing.conf> instead of
857 =head2 build_locate_components_service
859 This method is meant to provide a list of component modules that should be
860 setup for the application. By default, it will use L<Module::Pluggable>.
862 Specify a C<setup_components> config option to pass additional options directly
863 to L<Module::Pluggable>.
867 =head2 get_component_from_sub_container($sub_container, $name, $c, @args)
869 Looks for components in a given subcontainer (such as controller, model or
870 view), and returns the searched component. If $name is undef, it returns the
871 default component (such as default_view, if $sub_container is 'view'). If
872 $name is a regexp, it returns an array of matching components. Otherwise, it
873 looks for the component with name $name.
875 =head2 get_components_names_types
877 Gets all components from all containers and returns them as an array of
878 arrayrefs containing the component name and the component type (i.e., whether
879 it's an instance or a class).
881 =head2 get_all_components
883 Fetches all the components, in each of the sub_containers model, view and
884 controller, and returns a readonly hash. The keys are the class names, and
885 the values are the blessed objects. This is what is returned by $c->components.
889 Adds a component to the appropriate subcontainer. The subcontainer is guessed
890 by the component name given.
892 =head2 find_component
894 Searches for components in all containers. If $component is the full class
895 name, the subcontainer is guessed, and it gets the searched component in there.
896 Otherwise, it looks for a component with that name in all subcontainers. If
897 $component is a regexp, it calls the method below, find_component_regexp,
898 and matches all components against that regexp.
900 =head2 find_component_regexp
902 Finds components that match a given regexp. Used internally, by find_component.
904 =head2 expand_component_module
906 Components found by C<locate_components> will be passed to this method, which
907 is expected to return a list of component (package) names to be set up.
909 =head2 flush_request_services
911 =head2 setup_components
915 Catalyst Contributors, see Catalyst.pm
919 This library is free software. You can redistribute it and/or modify it under
920 the same terms as Perl itself.