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"}
82 $self->add_sub_container(
83 $self->build_controller_subcontainer
86 # FIXME - the config should be merged at this point
87 my $config = $self->resolve( service => 'config' );
88 my $default_view = $params->{default_view} || $config->{default_view};
89 my $default_model = $params->{default_model} || $config->{default_model};
91 $self->add_sub_container(
92 $self->build_view_subcontainer(
93 default_component => $default_view,
97 $self->add_sub_container(
98 $self->build_model_subcontainer(
99 default_component => $default_model,
104 sub build_model_subcontainer {
107 return $self->new_sub_container( @_,
112 sub build_view_subcontainer {
115 return $self->new_sub_container( @_,
120 sub build_controller_subcontainer {
123 return $self->new_sub_container(
124 name => 'controller',
128 sub build_application_name_service {
131 return Bread::Board::Literal->new( name => 'application_name', value => $self->application_name );
134 sub build_driver_service {
137 return Bread::Board::Literal->new( name => 'driver', value => $self->driver );
140 sub build_file_service {
143 return Bread::Board::Literal->new( name => 'file', value => $self->file );
146 sub build_substitutions_service {
149 return Bread::Board::Literal->new( name => 'substitutions', value => $self->substitutions );
152 sub build_extensions_service {
155 return Bread::Board::BlockInjection->new(
156 lifecycle => 'Singleton',
157 name => 'extensions',
159 return \@{Config::Any->extensions};
164 sub build_prefix_service {
167 return Bread::Board::BlockInjection->new(
168 lifecycle => 'Singleton',
171 return Catalyst::Utils::appprefix( shift->param('application_name') );
173 dependencies => [ depends_on('application_name') ],
177 sub build_path_service {
180 return Bread::Board::BlockInjection->new(
181 lifecycle => 'Singleton',
186 return Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG' )
188 || $s->param('application_name')->path_to( $s->param('prefix') );
190 dependencies => [ depends_on('file'), depends_on('application_name'), depends_on('prefix') ],
194 sub build_config_service {
197 return Bread::Board::BlockInjection->new(
198 lifecycle => 'Singleton',
203 my $v = Data::Visitor::Callback->new(
205 return unless defined $_;
206 return $self->_config_substitutions( $s->param('application_name'), $s->param('substitutions'), $_ );
210 $v->visit( $s->param('raw_config') );
212 dependencies => [ depends_on('application_name'), depends_on('raw_config'), depends_on('substitutions') ],
216 sub build_raw_config_service {
219 return Bread::Board::BlockInjection->new(
220 lifecycle => 'Singleton',
221 name => 'raw_config',
225 my @global = @{$s->param('global_config')};
226 my @locals = @{$s->param('local_config')};
229 for my $cfg (@global, @locals) {
231 $config = Catalyst::Utils::merge_hashes( $config, $cfg->{$_} );
236 dependencies => [ depends_on('global_config'), depends_on('local_config') ],
240 sub build_global_files_service {
243 return Bread::Board::BlockInjection->new(
244 lifecycle => 'Singleton',
245 name => 'global_files',
249 my ( $path, $extension ) = @{$s->param('config_path')};
251 my @extensions = @{$s->param('extensions')};
255 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
258 @files = map { "$path.$_" } @extensions;
262 dependencies => [ depends_on('extensions'), depends_on('config_path') ],
266 sub build_local_files_service {
269 return Bread::Board::BlockInjection->new(
270 lifecycle => 'Singleton',
271 name => 'local_files',
275 my ( $path, $extension ) = @{$s->param('config_path')};
276 my $suffix = $s->param('config_local_suffix');
278 my @extensions = @{$s->param('extensions')};
282 die "Unable to handle files with the extension '${extension}'" unless grep { $_ eq $extension } @extensions;
283 $path =~ s{\.$extension}{_$suffix.$extension};
286 @files = map { "${path}_${suffix}.$_" } @extensions;
290 dependencies => [ depends_on('extensions'), depends_on('config_path'), depends_on('config_local_suffix') ],
294 sub build_global_config_service {
297 return Bread::Board::BlockInjection->new(
298 lifecycle => 'Singleton',
299 name => 'global_config',
303 return Config::Any->load_files({
304 files => $s->param('global_files'),
305 filter => \&_fix_syntax,
307 driver_args => $s->param('driver'),
310 dependencies => [ depends_on('global_files') ],
314 sub build_local_config_service {
317 return Bread::Board::BlockInjection->new(
318 lifecycle => 'Singleton',
319 name => 'local_config',
323 return Config::Any->load_files({
324 files => $s->param('local_files'),
325 filter => \&_fix_syntax,
327 driver_args => $s->param('driver'),
330 dependencies => [ depends_on('local_files') ],
334 sub build_config_path_service {
337 return Bread::Board::BlockInjection->new(
338 lifecycle => 'Singleton',
339 name => 'config_path',
343 my $path = $s->param('path');
344 my $prefix = $s->param('prefix');
346 my ( $extension ) = ( $path =~ m{\.(.{1,4})$} );
349 $path =~ s{[\/\\]$}{};
353 return [ $path, $extension ];
355 dependencies => [ depends_on('prefix'), depends_on('path') ],
359 sub build_config_local_suffix_service {
362 return Bread::Board::BlockInjection->new(
363 lifecycle => 'Singleton',
364 name => 'config_local_suffix',
367 my $suffix = Catalyst::Utils::env_value( $s->param('application_name'), 'CONFIG_LOCAL_SUFFIX' ) || $self->config_local_suffix;
371 dependencies => [ depends_on('application_name') ],
375 sub build_locate_components_service {
378 return Bread::Board::BlockInjection->new(
379 lifecycle => 'Singleton',
380 name => 'locate_components',
383 my $class = $s->param('application_name');
384 my $config = $s->param('config')->{ setup_components };
386 Catalyst::Exception->throw(
387 qq{You are using search_extra config option. That option is\n} .
388 qq{deprecated, please refer to the documentation for\n} .
389 qq{other ways of achieving the same results.\n}
390 ) if delete $config->{ search_extra };
392 my @paths = qw( ::Controller ::C ::Model ::M ::View ::V );
394 my $locator = Module::Pluggable::Object->new(
395 search_path => [ map { s/^(?=::)/$class/; $_; } @paths ],
399 return [ $locator->plugins ];
401 dependencies => [ depends_on('application_name'), depends_on('config') ],
405 sub setup_components {
407 my $class = $self->resolve( service => 'application_name' );
408 my @comps = @{ $self->resolve( service => 'locate_components' ) };
409 my %comps = map { $_ => 1 } @comps;
410 my $deprecatedcatalyst_component_names = 0;
412 for my $component ( @comps ) {
414 # We pass ignore_loaded here so that overlay files for (e.g.)
415 # Model::DBI::Schema sub-classes are loaded - if it's in @comps
416 # we know M::P::O found a file on disk so this is safe
418 Catalyst::Utils::ensure_class_loaded( $component, { ignore_loaded => 1 } );
421 for my $component (@comps) {
422 $self->add_component( $component, $class );
423 # FIXME - $instance->expand_modules() is broken
424 my @expanded_components = $self->expand_component_module( $component );
427 !$deprecatedcatalyst_component_names &&
428 ($deprecatedcatalyst_component_names = $component =~ m/::[CMV]::/) ||
429 ($deprecatedcatalyst_component_names = grep { /::[CMV]::/ } @expanded_components)
431 # FIXME - should I be calling warn here?
432 $class->log->warn(qq{Your application is using the deprecated ::[MVC]:: type naming scheme.\n}.
433 qq{Please switch your class names to ::Model::, ::View:: and ::Controller: as appropriate.\n}
437 for my $component (@expanded_components) {
438 $self->add_component( $component, $class )
439 unless $comps{$component};
443 $self->get_sub_container('model')->make_single_default;
444 $self->get_sub_container('view')->make_single_default;
451 prefix => $_ eq 'Component' ? '' : $_ . '::',
452 values => delete $config->{ lc $_ } || delete $config->{ $_ }
454 grep { ref $config->{ lc $_ } || ref $config->{ $_ } }
455 qw( Component Model M View V Controller C Plugin )
458 foreach my $comp ( @components ) {
459 my $prefix = $comp->{ prefix };
460 foreach my $element ( keys %{ $comp->{ values } } ) {
461 $config->{ "$prefix$element" } = $comp->{ values }->{ $element };
466 sub _config_substitutions {
467 my ( $self, $name, $subs, $arg ) = @_;
469 $subs->{ HOME } ||= sub { shift->path_to( '' ); };
473 if (! defined($ENV{$v})) {
474 Catalyst::Exception->throw( message =>
475 "Missing environment variable: $v" );
481 $subs->{ path_to } ||= sub { shift->path_to( @_ ); };
482 $subs->{ literal } ||= sub { return $_[ 1 ]; };
483 my $subsre = join( '|', keys %$subs );
485 $arg =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $name, $2 ? split( /,/, $2 ) : () ) }eg;
489 sub get_component_from_sub_container {
490 my ( $self, $sub_container_name, $name, $c, @args ) = @_;
492 my $sub_container = $self->get_sub_container( $sub_container_name );
495 my $default = $sub_container->default_component;
497 return $sub_container->get_component( $default, $c, @args )
498 if $default && $sub_container->has_service( $default );
500 # FIXME - should I be calling $c->log->warn here?
501 # this is never a controller, so this is safe
502 $c->log->warn( "Calling \$c->$sub_container_name() is not supported unless you specify one of:" );
503 $c->log->warn( "* \$c->config(default_$sub_container_name => 'the name of the default $sub_container_name to use')" );
504 $c->log->warn( "* \$c->stash->{current_$sub_container_name} # the name of the view to use for this request" );
505 $c->log->warn( "* \$c->stash->{current_${sub_container_name}_instance} # the instance of the $sub_container_name to use for this request" );
510 return $sub_container->get_component_regexp( $name, $c, @args )
513 return $sub_container->get_component( $name, $c, @args )
514 if $sub_container->has_service( $name );
517 "Attempted to use $sub_container_name '$name', " .
518 "but it does not exist"
525 my ( $self, $component, $c, @args ) = @_;
526 my ( $type, $name ) = _get_component_type_name($component);
529 return $self->get_component_from_sub_container(
530 $type, $name, $c, @args
533 my $query = ref $component
538 for my $subcontainer_name (qw/model view controller/) {
539 my $subcontainer = $self->get_sub_container( $subcontainer_name );
540 my @components = $subcontainer->get_service_list;
541 @result = grep { m{$component} } @components;
543 return map { $subcontainer->get_component( $_, $c, @args ) } @result
547 # FIXME - I guess I shouldn't be calling $c->components here
548 # one last search for things like $c->comp(qr/::M::/)
549 @result = $self->find_component_regexp(
550 $c->components, $component, $c, @args
551 ) if !@result and ref $component;
553 # it expects an empty list on failed searches
557 sub find_component_regexp {
558 my ( $self, $components, $component, @args ) = @_;
561 my @components = grep { m{$component} } keys %{ $components };
564 my ($type, $name) = _get_component_type_name($_);
566 push @result, $self->get_component_from_sub_container(
574 # FIXME sorry for the name again :)
575 sub get_components_types {
579 for my $sub_container_name (qw/model view controller/) {
580 my $sub_container = $self->get_sub_container($sub_container_name);
581 for my $service ( $sub_container->get_service_list ) {
582 my $comp = $self->resolve(service => $service);
583 my $compname = ref $comp || $comp;
584 my $type = ref $comp ? 'instance' : 'class';
585 push @comps_types, [ $compname, $type ];
592 sub get_all_components {
597 map { $_ => $self->get_sub_container($_) } qw(model view controller)
600 for my $container (keys %$containers) {
601 for my $component ($containers->{$container}->get_service_list) {
602 my $comp = $containers->{$container}->resolve(
603 service => $component
605 my $comp_name = ref $comp || $comp;
606 $components{$comp_name} = $comp;
610 return lock_hash %components;
614 my ( $self, $component, $class ) = @_;
615 my ( $type, $name ) = _get_component_type_name($component);
619 $self->get_sub_container($type)->add_service(
620 Catalyst::IOC::ConstructorInjection->new(
621 lifecycle => 'Singleton', # FIXME?
625 depends_on( '/application_name' ),
626 depends_on( '/config' ),
631 default => Catalyst::Utils::class2classsuffix( $component ),
638 # FIXME: should this sub exist?
639 # should it be moved to Catalyst::Utils,
640 # or replaced by something already existing there?
641 sub _get_component_type_name {
642 my ( $component ) = @_;
644 my @parts = split /::/, $component;
646 while (my $type = shift @parts) {
647 return ('controller', join '::', @parts)
648 if $type =~ /^(c|controller)$/i;
650 return ('model', join '::', @parts)
651 if $type =~ /^(m|model)$/i;
653 return ('view', join '::', @parts)
654 if $type =~ /^(v|view)$/i;
657 return (undef, $component);
660 sub expand_component_module {
661 my ( $class, $module ) = @_;
662 return Devel::InnerPackage::list_packages( $module );
673 Catalyst::Container - IOC for Catalyst components
683 =head2 build_model_subcontainer
685 Container that stores all models.
687 =head2 build_view_subcontainer
689 Container that stores all views.
691 =head2 build_controller_subcontainer
693 Container that stores all controllers.
697 =head2 build_application_name_service
699 Name of the application (such as MyApp).
701 =head2 build_driver_service
703 Config options passed directly to the driver being used.
705 =head2 build_file_service
709 =head2 build_substitutions_service
711 Executes all the substitutions in config. See L</_config_substitutions> method.
713 =head2 build_extensions_service
715 =head2 build_prefix_service
717 =head2 build_path_service
719 =head2 build_config_service
721 =head2 build_raw_config_service
723 =head2 build_global_files_service
725 =head2 build_local_files_service
727 =head2 build_global_config_service
729 =head2 build_local_config_service
731 =head2 build_config_path_service
733 =head2 build_config_local_suffix_service
735 Determines the suffix of files used to override the main config. By default
736 this value is C<local>, which will load C<myapp_local.conf>. The suffix can
737 be specified in the following order of preference:
741 =item * C<$ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }>
743 =item * C<$ENV{ CATALYST_CONFIG_LOCAL_SUFFIX }>
747 The first one of these values found replaces the default of C<local> in the
748 name of the local config file to be loaded.
750 For example, if C< $ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }> is set to C<testing>,
751 ConfigLoader will try and load C<myapp_testing.conf> instead of
754 =head2 get_component_from_sub_container($sub_container, $name, $c, @args)
756 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.
758 =head2 get_components_types
760 =head2 get_all_components
762 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.
766 Adds a component to the appropriate subcontainer. The subcontainer is guessed by the component name given.
768 =head2 find_component
770 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.
772 =head2 find_component_regexp
774 Finds components that match a given regexp. Used internally, by find_component.
778 =head2 _config_substitutions
780 This method substitutes macros found with calls to a function. There are a
781 number of default macros:
785 =item * C<__HOME__> - replaced with C<$c-E<gt>path_to('')>
787 =item * C<__ENV(foo)__> - replaced with the value of C<$ENV{foo}>
789 =item * C<__path_to(foo/bar)__> - replaced with C<$c-E<gt>path_to('foo/bar')>
791 =item * C<__literal(__FOO__)__> - leaves __FOO__ alone (allows you to use
792 C<__DATA__> as a config value, for example)
796 The parameter list is split on comma (C<,>). You can override this method to
797 do your own string munging, or you can define your own macros in
798 C<MyApp-E<gt>config-E<gt>{ 'Plugin::ConfigLoader' }-E<gt>{ substitutions }>.
801 MyApp->config->{ 'Plugin::ConfigLoader' }->{ substitutions } = {
802 baz => sub { my $c = shift; qux( @_ ); }
805 The above will respond to C<__baz(x,y)__> in config strings.
807 =head2 $c->expand_component_module( $component, $setup_component_config )
809 Components found by C<locate_components> will be passed to this method, which
810 is expected to return a list of component (package) names to be set up.
812 =head2 build_locate_components_service
814 This method is meant to provide a list of component modules that should be
815 setup for the application. By default, it will use L<Module::Pluggable>.
817 Specify a C<setup_components> config option to pass additional options directly
818 to L<Module::Pluggable>.
820 =head2 setup_components
824 Catalyst Contributors, see Catalyst.pm
828 This library is free software. You can redistribute it and/or modify it under
829 the same terms as Perl itself.