1 package Catalyst::Controller;
4 use Moose::Util qw/find_meta/;
5 use List::MoreUtils qw/uniq/;
6 use namespace::clean -except => 'meta';
8 BEGIN { extends qw/Catalyst::Component MooseX::MethodAttributes::Inheritable/; }
10 use MooseX::MethodAttributes;
11 use Catalyst::Exception;
14 with 'Catalyst::Component::ApplicationAttribute';
21 predicate => 'has_path_prefix',
24 has action_namespace =>
28 init_arg => 'namespace',
29 predicate => 'has_action_namespace',
34 accessor => '_controller_actions',
39 # ->config(actions => { '*' => ...
40 has _all_actions_attributes => (
45 builder => '_build__all_actions_attributes',
49 my ($self, $args) = @_;
50 my $action = delete $args->{action} || {};
51 my $actions = delete $args->{actions} || {};
52 my $attr_value = $self->merge_config_hashes($actions, $action);
53 $self->_controller_actions($attr_value);
55 # trigger lazy builder
56 $self->_all_actions_attributes;
59 sub _build__all_actions_attributes {
61 delete $self->_controller_actions->{'*'} || {};
66 Catalyst::Controller - Catalyst Controller base class
70 package MyApp::Controller::Search
71 use base qw/Catalyst::Controller/;
74 my ($self,$c,@args) = @_;
76 } # Dispatches to /search/foo
80 Controllers are where the actions in the Catalyst framework
81 reside. Each action is represented by a function with an attribute to
82 identify what kind of action it is. See the L<Catalyst::Dispatcher>
83 for more info about how Catalyst dispatches to actions.
87 #I think both of these could be attributes. doesn't really seem like they need
88 #to ble class data. i think that attributes +default would work just fine
89 __PACKAGE__->mk_classdata($_) for qw/_dispatch_steps _action_class/;
91 __PACKAGE__->_dispatch_steps( [qw/_BEGIN _AUTO _ACTION/] );
92 __PACKAGE__->_action_class('Catalyst::Action');
95 sub _DISPATCH : Private {
96 my ( $self, $c ) = @_;
98 foreach my $disp ( @{ $self->_dispatch_steps } ) {
99 last unless $c->forward($disp);
105 sub _BEGIN : Private {
106 my ( $self, $c ) = @_;
107 my $begin = ( $c->get_actions( 'begin', $c->namespace ) )[-1];
108 return 1 unless $begin;
109 $begin->dispatch( $c );
110 return !@{ $c->error };
113 sub _AUTO : Private {
114 my ( $self, $c ) = @_;
115 my @auto = $c->get_actions( 'auto', $c->namespace );
116 foreach my $auto (@auto) {
117 $auto->dispatch( $c );
118 return 0 unless $c->state;
123 sub _ACTION : Private {
124 my ( $self, $c ) = @_;
126 && $c->action->can('execute')
127 && defined $c->req->action )
129 $c->action->dispatch( $c );
131 return !@{ $c->error };
135 my ( $self, $c ) = @_;
136 my $end = ( $c->get_actions( 'end', $c->namespace ) )[-1];
137 return 1 unless $end;
138 $end->dispatch( $c );
139 return !@{ $c->error };
143 my ( $self, $name ) = @_;
144 my $app = ($self->isa('Catalyst') ? $self : $self->_application);
145 return $app->dispatcher->get_action($name, $self->action_namespace);
148 #my opinion is that this whole sub really should be a builder method, not
149 #something that happens on every call. Anyone else disagree?? -- groditi
150 ## -- apparently this is all just waiting for app/ctx split
151 around action_namespace => sub {
153 my ( $self, $c ) = @_;
155 my $class = ref($self) || $self;
156 my $appclass = ref($c) || $c;
158 # FIXME - catalyst_component_name is no longer a class accessor, because
159 # 'MyApp as a controller' behavior is removed. But is this call to
160 # catalyst_component_name necessary, or is it always the same as $class?
161 my $component_name = ref($self) ? $self->catalyst_component_name : $self;
164 return $self->$orig if $self->has_action_namespace;
166 return $class->config->{namespace} if exists $class->config->{namespace};
171 $case_s = $appclass->config->{case_sensitive};
173 if ($self->isa('Catalyst')) {
174 $case_s = $class->config->{case_sensitive};
177 $case_s = ref($self->_application)->config->{case_sensitive};
179 confess("Can't figure out case_sensitive setting");
184 my $namespace = Catalyst::Utils::class2prefix($component_name, $case_s) || '';
185 $self->$orig($namespace) if ref($self);
189 #Once again, this is probably better written as a builder method
190 around path_prefix => sub {
194 return $self->$orig if $self->has_path_prefix;
196 return $self->config->{path} if exists $self->config->{path};
198 my $namespace = $self->action_namespace(@_);
199 $self->$orig($namespace) if ref($self);
203 sub get_action_methods {
205 my $meta = find_meta($self) || confess("No metaclass setup for $self");
207 sprintf "Metaclass %s for %s cannot support register_actions.",
208 ref $meta, $meta->name,
209 ) unless $meta->can('get_nearest_methods_with_attributes');
210 my @methods = $meta->get_nearest_methods_with_attributes;
212 # actions specified via config are also action_methods
216 $meta->find_method_by_name($_)
217 || confess( sprintf 'Action "%s" is not available from controller %s',
219 } keys %{ $self->_controller_actions }
221 return uniq @methods;
225 sub register_actions {
226 my ( $self, $c ) = @_;
227 $self->register_action_methods( $c, $self->get_action_methods );
230 sub register_action_methods {
231 my ( $self, $c, @methods ) = @_;
232 my $class = $self->catalyst_component_name;
233 #this is still not correct for some reason.
234 my $namespace = $self->action_namespace($c);
237 if (!blessed($self) && $self eq $c && scalar(@methods)) {
238 my @really_bad_methods = grep { ! /^_(DISPATCH|BEGIN|AUTO|ACTION|END)$/ } map { $_->name } @methods;
239 if (scalar(@really_bad_methods)) {
240 $c->log->warn("Action methods (" . join(', ', @really_bad_methods) . ") found defined in your application class, $self. This is deprecated, please move them into a Root controller.");
244 foreach my $method (@methods) {
245 my $name = $method->name;
246 # Horrible hack! All method metaclasses should have an attributes
247 # method, core Moose bug - see r13354.
248 my $attributes = $method->can('attributes') ? $method->attributes : [];
249 my $attrs = $self->_parse_attrs( $c, $name, @{ $attributes } );
250 if ( $attrs->{Private} && ( keys %$attrs > 1 ) ) {
251 $c->log->debug( 'Bad action definition "'
252 . join( ' ', @{ $attributes } )
253 . qq/" for "$class->$name"/ )
257 my $reverse = $namespace ? "${namespace}/${name}" : $name;
258 my $action = $self->create_action(
260 code => $method->body,
262 namespace => $namespace,
264 attributes => $attrs,
267 $c->dispatcher->register( $c, $action );
275 my $class = (exists $args{attributes}{ActionClass}
276 ? $args{attributes}{ActionClass}[0]
277 : $self->_action_class);
279 Class::MOP::load_class($class);
287 my $class = $self->action_class(%args);
288 my $action_args = $self->config->{action_args};
291 %{ $action_args->{'*'} || {} },
292 %{ $action_args->{ $args{name} } || {} },
295 return $class->new({ %extra_args, %args });
299 my ( $self, $c, $name, @attrs ) = @_;
303 foreach my $attr (@attrs) {
305 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
307 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+?)\s*\))?$/ ) )
310 if ( defined $value ) {
311 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
313 push( @{ $raw_attributes{$key} }, $value );
317 my ($actions_config, $all_actions_config);
319 $actions_config = $self->_controller_actions;
320 # No, you're not getting actions => { '*' => ... } with actions in MyApp.
321 $all_actions_config = $self->_all_actions_attributes;
323 my $cfg = $self->config;
324 $actions_config = $self->merge_config_hashes($cfg->{actions}, $cfg->{action});
325 $all_actions_config = {};
330 exists $actions_config->{$name} ? %{ $actions_config->{$name } } : (),
333 # Private actions with additional attributes will raise a warning and then
334 # be ignored. Adding '*' arguments to the default _DISPATCH / etc. methods,
335 # which are Private, will prevent those from being registered. They should
336 # probably be turned into :Actions instead, or we might want to otherwise
337 # disambiguate between those built-in internal actions and user-level
339 %raw_attributes = (%{ $all_actions_config }, %raw_attributes)
340 unless $raw_attributes{Private};
342 my %final_attributes;
344 foreach my $key (keys %raw_attributes) {
346 my $raw = $raw_attributes{$key};
348 foreach my $value (ref($raw) eq 'ARRAY' ? @$raw : $raw) {
350 my $meth = "_parse_${key}_attr";
351 if ( my $code = $self->can($meth) ) {
352 ( $key, $value ) = $self->$code( $c, $name, $value );
354 push( @{ $final_attributes{$key} }, $value );
358 return \%final_attributes;
361 sub _parse_Global_attr {
362 my ( $self, $c, $name, $value ) = @_;
363 return $self->_parse_Path_attr( $c, $name, "/$name" );
366 sub _parse_Absolute_attr { shift->_parse_Global_attr(@_); }
368 sub _parse_Local_attr {
369 my ( $self, $c, $name, $value ) = @_;
370 return $self->_parse_Path_attr( $c, $name, $name );
373 sub _parse_Relative_attr { shift->_parse_Local_attr(@_); }
375 sub _parse_Path_attr {
376 my ( $self, $c, $name, $value ) = @_;
377 $value = '' if !defined $value;
378 if ( $value =~ m!^/! ) {
379 return ( 'Path', $value );
381 elsif ( length $value ) {
382 return ( 'Path', join( '/', $self->path_prefix($c), $value ) );
385 return ( 'Path', $self->path_prefix($c) );
389 sub _parse_Regex_attr {
390 my ( $self, $c, $name, $value ) = @_;
391 return ( 'Regex', $value );
394 sub _parse_Regexp_attr { shift->_parse_Regex_attr(@_); }
396 sub _parse_LocalRegex_attr {
397 my ( $self, $c, $name, $value ) = @_;
398 unless ( $value =~ s/^\^// ) { $value = "(?:.*?)$value"; }
400 my $prefix = $self->path_prefix( $c );
401 $prefix .= '/' if length( $prefix );
403 return ( 'Regex', "^${prefix}${value}" );
406 sub _parse_LocalRegexp_attr { shift->_parse_LocalRegex_attr(@_); }
408 sub _parse_Chained_attr {
409 my ($self, $c, $name, $value) = @_;
411 if (defined($value) && length($value)) {
413 $value = '/'.$self->action_namespace($c);
414 } elsif (my ($rel, $rest) = $value =~ /^((?:\.{2}\/)+)(.*)$/) {
415 my @parts = split '/', $self->action_namespace($c);
416 my @levels = split '/', $rel;
418 $value = '/'.join('/', @parts[0 .. $#parts - @levels], $rest);
419 } elsif ($value !~ m/^\//) {
420 my $action_ns = $self->action_namespace($c);
423 $value = '/'.join('/', $action_ns, $value);
425 $value = '/'.$value; # special case namespace '' (root)
432 return Chained => $value;
435 sub _parse_ChainedParent_attr {
436 my ($self, $c, $name, $value) = @_;
437 return $self->_parse_Chained_attr($c, $name, '../'.$name);
440 sub _parse_PathPrefix_attr {
441 my ( $self, $c ) = @_;
442 return PathPart => $self->path_prefix($c);
445 sub _parse_ActionClass_attr {
446 my ( $self, $c, $name, $value ) = @_;
447 my $appname = $self->_application;
448 $value = Catalyst::Utils::resolve_namespace($appname . '::Action', $self->_action_class, $value);
449 return ( 'ActionClass', $value );
452 sub _parse_MyAction_attr {
453 my ( $self, $c, $name, $value ) = @_;
455 my $appclass = Catalyst::Utils::class2appclass($self);
456 $value = "${appclass}::Action::${value}";
458 return ( 'ActionClass', $value );
461 __PACKAGE__->meta->make_immutable;
469 Like any other L<Catalyst::Component>, controllers have a config hash,
470 accessible through $self->config from the controller actions. Some
471 settings are in use by the Catalyst framework:
475 This specifies the internal namespace the controller should be bound
476 to. By default the controller is bound to the URI version of the
477 controller name. For instance controller 'MyApp::Controller::Foo::Bar'
478 will be bound to 'foo/bar'. The default Root controller is an example
479 of setting namespace to '' (the null string).
483 Sets 'path_prefix', as described below.
487 Allows you to set the attributes that the dispatcher creates actions out of.
488 This allows you to do 'rails style routes', or override some of the
489 attribute defintions of actions composed from Roles.
490 You can set arguments globally (for all actions of the controller) and
491 specifically (for a single action).
495 '*' => { Chained => 'base', Args => 0 },
496 base => { Chained => '/', PathPart => '', CaptureArgs => 0 },
500 In the case above every sub in the package would be made into a Chain
501 endpoint with a URI the same as the sub name for each sub, chained
502 to the sub named C<base>. Ergo dispatch to C</example> would call the
503 C<base> method, then the C<example> method.
507 Allows you to set constructor arguments on your actions. You can set arguments
508 globally and specifically (as above).
509 This is particularly useful when using C<ActionRole>s
510 (L<Catalyst::Controller::ActionRole>) and custom C<ActionClass>es.
514 '*' => { globalarg1 => 'hello', globalarg2 => 'goodbye' },
515 'specific_action' => { customarg => 'arg1' },
519 In the case above the action class associated with C<specific_action> would get
520 passed the following arguments, in addition to the normal action constructor
521 arguments, when it is instantiated:
523 (globalarg1 => 'hello', globalarg2 => 'goodbye', customarg => 'arg1')
527 =head2 BUILDARGS ($app, @args)
529 From L<Catalyst::Component::ApplicationAttribute>, stashes the application
530 instance as $self->_application.
532 =head2 $self->action_for('name')
534 Returns the Catalyst::Action object (if any) for a given method name
537 =head2 $self->action_namespace($c)
539 Returns the private namespace for actions in this component. Defaults
540 to a value from the controller name (for
541 e.g. MyApp::Controller::Foo::Bar becomes "foo/bar") or can be
542 overridden from the "namespace" config key.
545 =head2 $self->path_prefix($c)
547 Returns the default path prefix for :PathPrefix, :Local, :LocalRegex and
548 relative :Path actions in this component. Defaults to the action_namespace or
549 can be overridden from the "path" config key.
551 =head2 $self->register_actions($c)
553 Finds all applicable actions for this component, creates
554 Catalyst::Action objects (using $self->create_action) for them and
555 registers them with $c->dispatcher.
557 =head2 $self->get_action_methods()
559 Returns a list of L<Moose::Meta::Method> objects, doing the
560 L<MooseX::MethodAttributes::Role::Meta::Method> role, which are the set of
561 action methods for this package.
563 =head2 $self->register_action_methods($c, @methods)
565 Creates action objects for a set of action methods using C< create_action >,
566 and registers them with the dispatcher.
568 =head2 $self->action_class(%args)
570 Used when a controller is creating an action to determine the correct base
573 =head2 $self->create_action(%args)
575 Called with a hash of data to be use for construction of a new
576 Catalyst::Action (or appropriate sub/alternative class) object.
578 =head2 $self->_application
582 Returns the application instance stored by C<new()>
586 Catalyst Contributors, see Catalyst.pm
590 This library is free software. You can redistribute it and/or modify
591 it under the same terms as Perl itself.