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 )
113 sub build_model_subcontainer {
116 return $self->new_sub_container( @_,
121 sub build_view_subcontainer {
124 return $self->new_sub_container( @_,
129 sub build_controller_subcontainer {
132 return $self->new_sub_container(
133 name => 'controller',
137 sub build_component_subcontainer {
140 return Bread::Board::Container->new(
145 sub build_application_name_service {
148 return Bread::Board::Literal->new( name => 'application_name', value => $self->application_name );
151 sub build_driver_service {
154 return Bread::Board::Literal->new( name => 'driver', value => $self->driver );
157 sub build_file_service {
160 return Bread::Board::Literal->new( name => 'file', value => $self->file );
163 sub build_substitutions_service {
166 return Bread::Board::Literal->new( name => 'substitutions', value => $self->substitutions );
169 sub build_extensions_service {
172 return Bread::Board::BlockInjection->new(
173 lifecycle => 'Singleton',
174 name => 'extensions',
176 return \@{Config::Any->extensions};
181 sub build_prefix_service {
184 return Bread::Board::BlockInjection->new(
185 lifecycle => 'Singleton',
188 return Catalyst::Utils::appprefix( shift->param('application_name') );
190 dependencies => [ depends_on('application_name') ],
194 sub build_path_service {
197 return Bread::Board::BlockInjection->new(
198 lifecycle => 'Singleton',
203 return Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG' )
205 || $s->param('application_name')->path_to( $s->param('prefix') );
207 dependencies => [ depends_on('file'), depends_on('application_name'), depends_on('prefix') ],
211 sub build_config_service {
214 return Bread::Board::BlockInjection->new(
215 lifecycle => 'Singleton',
220 my $v = Data::Visitor::Callback->new(
222 return unless defined $_;
223 return $self->_config_substitutions( $s->param('application_name'), $s->param('substitutions'), $_ );
227 $v->visit( $s->param('raw_config') );
229 dependencies => [ depends_on('application_name'), depends_on('raw_config'), depends_on('substitutions') ],
233 sub build_raw_config_service {
236 return Bread::Board::BlockInjection->new(
237 lifecycle => 'Singleton',
238 name => 'raw_config',
242 my @global = @{$s->param('global_config')};
243 my @locals = @{$s->param('local_config')};
245 my $config = $s->param('class_config');
247 for my $cfg (@global, @locals) {
249 $config = Catalyst::Utils::merge_hashes( $config, $cfg->{$_} );
255 dependencies => [ depends_on('global_config'), depends_on('local_config'), depends_on('class_config') ],
259 sub build_global_files_service {
262 return Bread::Board::BlockInjection->new(
263 lifecycle => 'Singleton',
264 name => 'global_files',
268 my ( $path, $extension ) = @{$s->param('config_path')};
270 my @extensions = @{$s->param('extensions')};
274 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
277 @files = map { "$path.$_" } @extensions;
281 dependencies => [ depends_on('extensions'), depends_on('config_path') ],
285 sub build_local_files_service {
288 return Bread::Board::BlockInjection->new(
289 lifecycle => 'Singleton',
290 name => 'local_files',
294 my ( $path, $extension ) = @{$s->param('config_path')};
295 my $suffix = $s->param('config_local_suffix');
297 my @extensions = @{$s->param('extensions')};
301 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
302 $path =~ s{\.$extension}{_$suffix.$extension};
305 @files = map { "${path}_${suffix}.$_" } @extensions;
309 dependencies => [ depends_on('extensions'), depends_on('config_path'), depends_on('config_local_suffix') ],
313 sub build_class_config_service {
316 return Bread::Board::BlockInjection->new(
317 lifecycle => 'Singleton',
318 name => 'class_config',
321 my $app = $s->param('application_name');
323 # Container might be called outside Catalyst context
324 return {} unless Class::MOP::is_class_loaded($app);
326 # config might not have been defined
327 return $app->config || {};
329 dependencies => [ depends_on('application_name') ],
333 sub build_global_config_service {
336 return Bread::Board::BlockInjection->new(
337 lifecycle => 'Singleton',
338 name => 'global_config',
342 return Config::Any->load_files({
343 files => $s->param('global_files'),
344 filter => \&_fix_syntax,
346 driver_args => $s->param('driver'),
349 dependencies => [ depends_on('global_files') ],
353 sub build_local_config_service {
356 return Bread::Board::BlockInjection->new(
357 lifecycle => 'Singleton',
358 name => 'local_config',
362 return Config::Any->load_files({
363 files => $s->param('local_files'),
364 filter => \&_fix_syntax,
366 driver_args => $s->param('driver'),
369 dependencies => [ depends_on('local_files') ],
373 sub build_config_path_service {
376 return Bread::Board::BlockInjection->new(
377 lifecycle => 'Singleton',
378 name => 'config_path',
382 my $path = $s->param('path');
383 my $prefix = $s->param('prefix');
385 my ( $extension ) = ( $path =~ m{\.(.{1,4})$} );
388 $path =~ s{[\/\\]$}{};
392 return [ $path, $extension ];
394 dependencies => [ depends_on('prefix'), depends_on('path') ],
398 sub build_config_local_suffix_service {
401 return Bread::Board::BlockInjection->new(
402 lifecycle => 'Singleton',
403 name => 'config_local_suffix',
406 my $suffix = Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG_LOCAL_SUFFIX' ) || $self->config_local_suffix;
410 dependencies => [ depends_on('application_name') ],
414 sub build_locate_components_service {
417 return Bread::Board::BlockInjection->new(
418 lifecycle => 'Singleton',
419 name => 'locate_components',
422 my $class = $s->param('application_name');
423 my $config = $s->param('config')->{ setup_components };
425 Catalyst::Exception->throw(
426 qq{You are using search_extra config option. That option is\n} .
427 qq{deprecated, please refer to the documentation for\n} .
428 qq{other ways of achieving the same results.\n}
429 ) if delete $config->{ search_extra };
431 my @paths = qw( ::Controller ::C ::Model ::M ::View ::V );
433 my $locator = Module::Pluggable::Object->new(
434 search_path => [ map { s/^(?=::)/$class/; $_; } @paths ],
438 return [ $locator->plugins ];
440 dependencies => [ depends_on('application_name'), depends_on('config') ],
444 sub setup_components {
446 my $class = $self->resolve( service => 'application_name' );
447 my @comps = @{ $self->resolve( service => 'locate_components' ) };
448 my %comps = map { $_ => 1 } @comps;
449 my $deprecatedcatalyst_component_names = 0;
451 for my $component ( @comps ) {
453 # We pass ignore_loaded here so that overlay files for (e.g.)
454 # Model::DBI::Schema sub-classes are loaded - if it's in @comps
455 # we know M::P::O found a file on disk so this is safe
457 Catalyst::Utils::ensure_class_loaded( $component, { ignore_loaded => 1 } );
460 for my $component (@comps) {
461 $self->add_component( $component );
462 # FIXME - $instance->expand_modules() is broken
463 my @expanded_components = $self->expand_component_module( $component );
466 !$deprecatedcatalyst_component_names &&
467 ($deprecatedcatalyst_component_names = $component =~ m/::[CMV]::/) ||
468 ($deprecatedcatalyst_component_names = grep { /::[CMV]::/ } @expanded_components)
470 # FIXME - should I be calling warn here?
471 # Maybe it's time to remove it, or become fatal
472 $class->log->warn(qq{Your application is using the deprecated ::[MVC]:: type naming scheme.\n}.
473 qq{Please switch your class names to ::Model::, ::View:: and ::Controller: as appropriate.\n}
477 for my $component (@expanded_components) {
478 $self->add_component( $component )
479 unless $comps{$component};
488 prefix => $_ eq 'Component' ? '' : $_ . '::',
489 values => delete $config->{ lc $_ } || delete $config->{ $_ }
491 grep { ref $config->{ lc $_ } || ref $config->{ $_ } }
492 qw( Component Model M View V Controller C Plugin )
495 foreach my $comp ( @components ) {
496 my $prefix = $comp->{ prefix };
497 foreach my $element ( keys %{ $comp->{ values } } ) {
498 $config->{ "$prefix$element" } = $comp->{ values }->{ $element };
503 sub _config_substitutions {
504 my ( $self, $name, $subs, $arg ) = @_;
506 $subs->{ HOME } ||= sub { shift->path_to( '' ); };
510 if (! defined($ENV{$v})) {
511 Catalyst::Exception->throw( message =>
512 "Missing environment variable: $v" );
518 $subs->{ path_to } ||= sub { shift->path_to( @_ ); };
519 $subs->{ literal } ||= sub { return $_[ 1 ]; };
520 my $subsre = join( '|', keys %$subs );
522 $arg =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $name, $2 ? split( /,/, $2 ) : () ) }eg;
526 sub get_component_from_sub_container {
527 my ( $self, $sub_container_name, $name, $c, @args ) = @_;
529 my $sub_container = $self->get_sub_container( $sub_container_name );
532 my $default = $sub_container->default_component;
534 return $sub_container->get_component( $default, $c, @args )
535 if $default && $sub_container->has_service( $default );
537 # FIXME - should I be calling $c->log->warn here?
538 # this is never a controller, so this is safe
539 $c->log->warn( "Calling \$c->$sub_container_name() is not supported unless you specify one of:" );
540 $c->log->warn( "* \$c->config(default_$sub_container_name => 'the name of the default $sub_container_name to use')" );
541 $c->log->warn( "* \$c->stash->{current_$sub_container_name} # the name of the view to use for this request" );
542 $c->log->warn( "* \$c->stash->{current_${sub_container_name}_instance} # the instance of the $sub_container_name to use for this request" );
547 return $sub_container->get_component_regexp( $name, $c, @args )
550 return $sub_container->get_component( $name, $c, @args )
551 if $sub_container->has_service( $name );
554 "Attempted to use $sub_container_name '$name', " .
555 "but it does not exist"
562 my ( $self, $component, @args ) = @_;
563 my ( $type, $name ) = _get_component_type_name($component);
566 return $self->get_component_from_sub_container(
570 my $query = ref $component
575 for my $subcontainer_name (qw/model view controller/) {
576 my $subcontainer = $self->get_sub_container( $subcontainer_name );
577 my @components = $subcontainer->get_service_list;
578 @result = grep { m{$component} } @components;
580 return map { $subcontainer->get_component( $_, @args ) } @result
584 # one last search for things like $c->comp(qr/::M::/)
585 @result = $self->_find_component_regexp(
587 ) if !@result and ref $component;
589 # it expects an empty list on failed searches
593 sub _find_component_regexp {
594 my ( $self, $component, @args ) = @_;
597 my @components = grep { m{$component} } keys %{ $self->get_all_components };
600 my ($type, $name) = _get_component_type_name($_);
602 push @result, $self->get_component_from_sub_container(
610 sub get_all_components {
614 foreach my $type (qw/model view controller /) {
615 my $container = $self->get_sub_container('component');
617 for my $component ($container->get_service_list) {
618 my $comp = $container->resolve(
619 service => $component
621 my $comp_name = ref $comp || $comp; # THIS IS WRONG! :)
622 # Just as it is called Model::Foo
623 # does not mean it has to be
624 # an instance of model::foo
625 $components{$comp_name} = $comp;
629 return lock_hash %components;
633 my ( $self, $component ) = @_;
634 my ( $type, $name ) = _get_component_type_name($component);
638 my $component_service_name = "${type}_${name}";
640 # The 'component' sub-container will create the object, and store it's
641 # instance, which, by default, will live throughout the application.
642 # The model/view/controller sub-containers only reference the instance
643 # held in the aforementioned sub-container, and execute the ACCEPT_CONTEXT
644 # sub every time they are called, when it exists.
645 my $instance_container = $self->get_sub_container('component');
646 my $accept_context_container = $self->get_sub_container($type);
648 $instance_container->add_service(
649 Catalyst::IOC::ConstructorInjection->new(
650 name => $component_service_name,
652 lifecycle => 'Singleton',
654 depends_on( '/application_name' ),
655 depends_on( '/config' ),
658 ) unless $instance_container->has_service( $component_service_name );
659 # ^ custom containers might have added the service already.
660 # we don't want to override that.
662 $accept_context_container->add_service(
663 Catalyst::IOC::BlockInjection->new(
666 depends_on( "/component/$component_service_name" ),
668 block => sub { shift->param($component_service_name) },
670 ) unless $accept_context_container->has_service( $name );
674 # FIXME: should this sub exist?
675 # should it be moved to Catalyst::Utils,
676 # or replaced by something already existing there?
677 sub _get_component_type_name {
678 my ( $component ) = @_;
681 while ( !$result and (my $index = index $component, '::') > 0 ) {
682 my $type = lc substr $component, 0, $index;
683 $component = substr $component, $index + 2;
684 $result = first { $type eq $_ or $type eq substr($_, 0, 1) }
685 qw{ model view controller };
688 return ($result, $component);
691 sub expand_component_module {
692 my ( $class, $module ) = @_;
693 return Devel::InnerPackage::list_packages( $module );
704 Catalyst::Container - IOC for Catalyst components
712 =head1 Building Containers
714 =head2 build_component_subcontainer
716 Container that stores all components, i.e. all models, views and controllers
717 together. Each service is an instance of the actual component, and by default
718 it lives while the application is running. Retrieving components from this
719 subcontainer will instantiate the component, if it hasn't been instantiated
720 already, but will not execute ACCEPT_CONTEXT.
722 =head2 build_model_subcontainer
724 Container that stores references for all models that are inside the components
725 subcontainer. Retrieving a model triggers ACCEPT_CONTEXT, if it exists.
727 =head2 build_view_subcontainer
729 Same as L<build_model_subcontainer>, but for views.
731 =head2 build_controller_subcontainer
733 Same as L<build_model_subcontainer>, but for controllers.
735 =head1 Building Services
737 =head2 build_application_name_service
739 Name of the application (such as MyApp).
741 =head2 build_driver_service
743 Config options passed directly to the driver being used.
745 =head2 build_file_service
749 =head2 build_substitutions_service
751 This method substitutes macros found with calls to a function. There are a
752 number of default macros:
756 =item * C<__HOME__> - replaced with C<$c-E<gt>path_to('')>
758 =item * C<__ENV(foo)__> - replaced with the value of C<$ENV{foo}>
760 =item * C<__path_to(foo/bar)__> - replaced with C<$c-E<gt>path_to('foo/bar')>
762 =item * C<__literal(__FOO__)__> - leaves __FOO__ alone (allows you to use
763 C<__DATA__> as a config value, for example)
767 The parameter list is split on comma (C<,>). You can override this method to
768 do your own string munging, or you can define your own macros in
769 C<< <MyApp->config( 'Plugin::ConfigLoader' => { substitutions => { ... } } ) >>.
772 MyApp->config( 'Plugin::ConfigLoader' => {
774 baz => sub { my $c = shift; qux( @_ ); },
778 The above will respond to C<__baz(x,y)__> in config strings.
780 =head2 build_extensions_service
782 Config::Any's available config file extensions (e.g. xml, json, pl, etc).
784 =head2 build_prefix_service
786 The prefix, based on the application name, that will be used to lookup the
787 config files (which will be in the format $prefix.$extension). If the app is
788 MyApp::Foo, the prefix will be myapp_foo.
790 =head2 build_path_service
792 The path to the config file (or environment variable, if defined).
794 =head2 build_config_service
796 The resulting configuration for the application, after it has successfully
797 been loaded, and all substitutions have been made.
799 =head2 build_raw_config_service
801 The merge of local_config and global_config hashes, before substitutions.
803 =head2 build_global_files_service
805 Gets all files for config that don't have the local_suffix, such as myapp.conf.
807 =head2 build_local_files_service
809 Gets all files for config that have the local_suffix, such as myapp_local.conf.
811 =head2 build_global_config_service
813 Reads config from global_files.
815 =head2 build_local_config_service
817 Reads config from local_files.
819 =head2 build_class_config_service
821 Reads config set from the application's class attribute config,
822 i.e. MyApp->config( name => 'MyApp', ... )
824 =head2 build_config_path_service
826 Splits the path to the config file, and returns on array ref containing
827 the path to the config file minus the extension in the first position,
828 and the extension in the second.
830 =head2 build_config_local_suffix_service
832 Determines the suffix of files used to override the main config. By default
833 this value is C<local>, which will load C<myapp_local.conf>. The suffix can
834 be specified in the following order of preference:
838 =item * C<$ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }>
840 =item * C<$ENV{ CATALYST_CONFIG_LOCAL_SUFFIX }>
844 The first one of these values found replaces the default of C<local> in the
845 name of the local config file to be loaded.
847 For example, if C< $ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }> is set to C<testing>,
848 ConfigLoader will try and load C<myapp_testing.conf> instead of
851 =head2 build_locate_components_service
853 This method is meant to provide a list of component modules that should be
854 setup for the application. By default, it will use L<Module::Pluggable>.
856 Specify a C<setup_components> config option to pass additional options directly
857 to L<Module::Pluggable>.
861 =head2 get_component_from_sub_container($sub_container, $name, $c, @args)
863 Looks for components in a given subcontainer (such as controller, model or
864 view), and returns the searched component. If $name is undef, it returns the
865 default component (such as default_view, if $sub_container is 'view'). If
866 $name is a regexp, it returns an array of matching components. Otherwise, it
867 looks for the component with name $name.
869 =head2 get_all_components
871 Fetches all the components, in each of the sub_containers model, view and
872 controller, and returns a readonly hash. The keys are the class names, and
873 the values are the blessed objects. This is what is returned by $c->components.
877 Adds a component to the appropriate subcontainer. The subcontainer is guessed
878 by the component name given.
880 =head2 find_component
882 Searches for components in all containers. If $component is the full class
883 name, the subcontainer is guessed, and it gets the searched component in there.
884 Otherwise, it looks for a component with that name in all subcontainers. If
885 $component is a regexp it calls _find_component_regexp and matches all
886 components against that regexp.
888 =head2 expand_component_module
890 Components found by C<locate_components> will be passed to this method, which
891 is expected to return a list of component (package) names to be set up.
893 =head2 setup_components
897 Catalyst Contributors, see Catalyst.pm
901 This library is free software. You can redistribute it and/or modify it under
902 the same terms as Perl itself.