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 has action_args => (is => 'ro');
41 # ->config(actions => { '*' => ...
42 has _all_actions_attributes => (
47 builder => '_build__all_actions_attributes',
51 my ($self, $args) = @_;
52 my $action = delete $args->{action} || {};
53 my $actions = delete $args->{actions} || {};
54 my $attr_value = $self->merge_config_hashes($actions, $action);
55 $self->_controller_actions($attr_value);
57 # trigger lazy builder
58 $self->_all_actions_attributes;
61 sub _build__all_actions_attributes {
63 delete $self->_controller_actions->{'*'} || {};
68 Catalyst::Controller - Catalyst Controller base class
72 package MyApp::Controller::Search
73 use base qw/Catalyst::Controller/;
76 my ($self,$c,@args) = @_;
78 } # Dispatches to /search/foo
82 Controllers are where the actions in the Catalyst framework
83 reside. Each action is represented by a function with an attribute to
84 identify what kind of action it is. See the L<Catalyst::Dispatcher>
85 for more info about how Catalyst dispatches to actions.
89 #I think both of these could be attributes. doesn't really seem like they need
90 #to ble class data. i think that attributes +default would work just fine
91 __PACKAGE__->mk_classdata($_) for qw/_dispatch_steps _action_class/;
93 __PACKAGE__->_dispatch_steps( [qw/_BEGIN _AUTO _ACTION/] );
94 __PACKAGE__->_action_class('Catalyst::Action');
97 sub _DISPATCH : Private {
98 my ( $self, $c ) = @_;
100 foreach my $disp ( @{ $self->_dispatch_steps } ) {
101 last unless $c->forward($disp);
107 sub _BEGIN : Private {
108 my ( $self, $c ) = @_;
109 my $begin = ( $c->get_actions( 'begin', $c->namespace ) )[-1];
110 return 1 unless $begin;
111 $begin->dispatch( $c );
112 return !@{ $c->error };
115 sub _AUTO : Private {
116 my ( $self, $c ) = @_;
117 my @auto = $c->get_actions( 'auto', $c->namespace );
118 foreach my $auto (@auto) {
119 $auto->dispatch( $c );
120 return 0 unless $c->state;
125 sub _ACTION : Private {
126 my ( $self, $c ) = @_;
128 && $c->action->can('execute')
129 && defined $c->req->action )
131 $c->action->dispatch( $c );
133 return !@{ $c->error };
137 my ( $self, $c ) = @_;
138 my $end = ( $c->get_actions( 'end', $c->namespace ) )[-1];
139 return 1 unless $end;
140 $end->dispatch( $c );
141 return !@{ $c->error };
145 my ( $self, $name ) = @_;
146 my $app = ($self->isa('Catalyst') ? $self : $self->_application);
147 return $app->dispatcher->get_action($name, $self->action_namespace);
150 #my opinion is that this whole sub really should be a builder method, not
151 #something that happens on every call. Anyone else disagree?? -- groditi
152 ## -- apparently this is all just waiting for app/ctx split
153 around action_namespace => sub {
155 my ( $self, $c ) = @_;
157 my $class = ref($self) || $self;
158 my $appclass = ref($c) || $c;
160 return $self->$orig if $self->has_action_namespace;
162 return $class->config->{namespace} if exists $class->config->{namespace};
167 $case_s = $appclass->config->{case_sensitive};
169 if ($self->isa('Catalyst')) {
170 $case_s = $class->config->{case_sensitive};
173 $case_s = ref($self->_application)->config->{case_sensitive};
175 confess("Can't figure out case_sensitive setting");
180 my $namespace = Catalyst::Utils::class2prefix($self->catalyst_component_name, $case_s) || '';
181 $self->$orig($namespace) if ref($self);
185 #Once again, this is probably better written as a builder method
186 around path_prefix => sub {
190 return $self->$orig if $self->has_path_prefix;
192 return $self->config->{path} if exists $self->config->{path};
194 my $namespace = $self->action_namespace(@_);
195 $self->$orig($namespace) if ref($self);
199 sub get_action_methods {
201 my $meta = find_meta($self) || confess("No metaclass setup for $self");
203 sprintf "Metaclass %s for %s cannot support register_actions.",
204 ref $meta, $meta->name,
205 ) unless $meta->can('get_nearest_methods_with_attributes');
206 my @methods = $meta->get_nearest_methods_with_attributes;
208 # actions specified via config are also action_methods
212 $meta->find_method_by_name($_)
213 || confess( sprintf 'Action "%s" is not available from controller %s',
215 } keys %{ $self->_controller_actions }
217 return uniq @methods;
221 sub register_actions {
222 my ( $self, $c ) = @_;
223 $self->register_action_methods( $c, $self->get_action_methods );
226 sub register_action_methods {
227 my ( $self, $c, @methods ) = @_;
228 my $class = $self->catalyst_component_name;
229 #this is still not correct for some reason.
230 my $namespace = $self->action_namespace($c);
233 if (!blessed($self) && $self eq $c && scalar(@methods)) {
234 my @really_bad_methods = grep { ! /^_(DISPATCH|BEGIN|AUTO|ACTION|END)$/ } map { $_->name } @methods;
235 if (scalar(@really_bad_methods)) {
236 $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.");
240 foreach my $method (@methods) {
241 my $name = $method->name;
242 # Horrible hack! All method metaclasses should have an attributes
243 # method, core Moose bug - see r13354.
244 my $attributes = $method->can('attributes') ? $method->attributes : [];
245 my $attrs = $self->_parse_attrs( $c, $name, @{ $attributes } );
246 if ( $attrs->{Private} && ( keys %$attrs > 1 ) ) {
247 $c->log->debug( 'Bad action definition "'
248 . join( ' ', @{ $attributes } )
249 . qq/" for "$class->$name"/ )
253 my $reverse = $namespace ? "${namespace}/${name}" : $name;
254 my $action = $self->create_action(
256 code => $method->body,
258 namespace => $namespace,
260 attributes => $attrs,
263 $c->dispatcher->register( $c, $action );
271 my $class = (exists $args{attributes}{ActionClass}
272 ? $args{attributes}{ActionClass}[0]
273 : $self->_action_class);
275 Class::MOP::load_class($class);
283 my $class = $self->action_class(%args);
287 : $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 # Note we deep copy array refs here to stop crapping on config
331 # when attributes are parsed. RT#65463
332 exists $actions_config->{$name} ? map { ref($_) eq 'ARRAY' ? [ @$_ ] : $_ } %{ $actions_config->{$name } } : (),
335 # Private actions with additional attributes will raise a warning and then
336 # be ignored. Adding '*' arguments to the default _DISPATCH / etc. methods,
337 # which are Private, will prevent those from being registered. They should
338 # probably be turned into :Actions instead, or we might want to otherwise
339 # disambiguate between those built-in internal actions and user-level
341 %raw_attributes = (%{ $all_actions_config }, %raw_attributes)
342 unless $raw_attributes{Private};
344 my %final_attributes;
346 foreach my $key (keys %raw_attributes) {
348 my $raw = $raw_attributes{$key};
350 foreach my $value (ref($raw) eq 'ARRAY' ? @$raw : $raw) {
352 my $meth = "_parse_${key}_attr";
353 if ( my $code = $self->can($meth) ) {
354 ( $key, $value ) = $self->$code( $c, $name, $value );
356 push( @{ $final_attributes{$key} }, $value );
360 return \%final_attributes;
363 sub _parse_Global_attr {
364 my ( $self, $c, $name, $value ) = @_;
365 return $self->_parse_Path_attr( $c, $name, "/$name" );
368 sub _parse_Absolute_attr { shift->_parse_Global_attr(@_); }
370 sub _parse_Local_attr {
371 my ( $self, $c, $name, $value ) = @_;
372 return $self->_parse_Path_attr( $c, $name, $name );
375 sub _parse_Relative_attr { shift->_parse_Local_attr(@_); }
377 sub _parse_Path_attr {
378 my ( $self, $c, $name, $value ) = @_;
379 $value = '' if !defined $value;
380 if ( $value =~ m!^/! ) {
381 return ( 'Path', $value );
383 elsif ( length $value ) {
384 return ( 'Path', join( '/', $self->path_prefix($c), $value ) );
387 return ( 'Path', $self->path_prefix($c) );
391 sub _parse_Regex_attr {
392 my ( $self, $c, $name, $value ) = @_;
393 return ( 'Regex', $value );
396 sub _parse_Regexp_attr { shift->_parse_Regex_attr(@_); }
398 sub _parse_LocalRegex_attr {
399 my ( $self, $c, $name, $value ) = @_;
400 unless ( $value =~ s/^\^// ) { $value = "(?:.*?)$value"; }
402 my $prefix = $self->path_prefix( $c );
403 $prefix .= '/' if length( $prefix );
405 return ( 'Regex', "^${prefix}${value}" );
408 sub _parse_LocalRegexp_attr { shift->_parse_LocalRegex_attr(@_); }
410 sub _parse_Chained_attr {
411 my ($self, $c, $name, $value) = @_;
413 if (defined($value) && length($value)) {
415 $value = '/'.$self->action_namespace($c);
416 } elsif (my ($rel, $rest) = $value =~ /^((?:\.{2}\/)+)(.*)$/) {
417 my @parts = split '/', $self->action_namespace($c);
418 my @levels = split '/', $rel;
420 $value = '/'.join('/', @parts[0 .. $#parts - @levels], $rest);
421 } elsif ($value !~ m/^\//) {
422 my $action_ns = $self->action_namespace($c);
425 $value = '/'.join('/', $action_ns, $value);
427 $value = '/'.$value; # special case namespace '' (root)
434 return Chained => $value;
437 sub _parse_ChainedParent_attr {
438 my ($self, $c, $name, $value) = @_;
439 return $self->_parse_Chained_attr($c, $name, '../'.$name);
442 sub _parse_PathPrefix_attr {
443 my ( $self, $c ) = @_;
444 return PathPart => $self->path_prefix($c);
447 sub _parse_ActionClass_attr {
448 my ( $self, $c, $name, $value ) = @_;
449 my $appname = $self->_application;
450 $value = Catalyst::Utils::resolve_namespace($appname . '::Action', $self->_action_class, $value);
451 return ( 'ActionClass', $value );
454 sub _parse_MyAction_attr {
455 my ( $self, $c, $name, $value ) = @_;
457 my $appclass = Catalyst::Utils::class2appclass($self);
458 $value = "${appclass}::Action::${value}";
460 return ( 'ActionClass', $value );
463 __PACKAGE__->meta->make_immutable;
471 Like any other L<Catalyst::Component>, controllers have a config hash,
472 accessible through $self->config from the controller actions. Some
473 settings are in use by the Catalyst framework:
477 This specifies the internal namespace the controller should be bound
478 to. By default the controller is bound to the URI version of the
479 controller name. For instance controller 'MyApp::Controller::Foo::Bar'
480 will be bound to 'foo/bar'. The default Root controller is an example
481 of setting namespace to '' (the null string).
485 Sets 'path_prefix', as described below.
489 Allows you to set the attributes that the dispatcher creates actions out of.
490 This allows you to do 'rails style routes', or override some of the
491 attribute definitions of actions composed from Roles.
492 You can set arguments globally (for all actions of the controller) and
493 specifically (for a single action).
497 '*' => { Chained => 'base', Args => 0 },
498 base => { Chained => '/', PathPart => '', CaptureArgs => 0 },
502 In the case above every sub in the package would be made into a Chain
503 endpoint with a URI the same as the sub name for each sub, chained
504 to the sub named C<base>. Ergo dispatch to C</example> would call the
505 C<base> method, then the C<example> method.
509 Allows you to set constructor arguments on your actions. You can set arguments
510 globally and specifically (as above).
511 This is particularly useful when using C<ActionRole>s
512 (L<Catalyst::Controller::ActionRole>) and custom C<ActionClass>es.
516 '*' => { globalarg1 => 'hello', globalarg2 => 'goodbye' },
517 'specific_action' => { customarg => 'arg1' },
521 In the case above the action class associated with C<specific_action> would get
522 passed the following arguments, in addition to the normal action constructor
523 arguments, when it is instantiated:
525 (globalarg1 => 'hello', globalarg2 => 'goodbye', customarg => 'arg1')
529 =head2 BUILDARGS ($app, @args)
531 From L<Catalyst::Component::ApplicationAttribute>, stashes the application
532 instance as $self->_application.
534 =head2 $self->action_for('name')
536 Returns the Catalyst::Action object (if any) for a given method name
539 =head2 $self->action_namespace($c)
541 Returns the private namespace for actions in this component. Defaults
542 to a value from the controller name (for
543 e.g. MyApp::Controller::Foo::Bar becomes "foo/bar") or can be
544 overridden from the "namespace" config key.
547 =head2 $self->path_prefix($c)
549 Returns the default path prefix for :PathPrefix, :Local, :LocalRegex and
550 relative :Path actions in this component. Defaults to the action_namespace or
551 can be overridden from the "path" config key.
553 =head2 $self->register_actions($c)
555 Finds all applicable actions for this component, creates
556 Catalyst::Action objects (using $self->create_action) for them and
557 registers them with $c->dispatcher.
559 =head2 $self->get_action_methods()
561 Returns a list of L<Moose::Meta::Method> objects, doing the
562 L<MooseX::MethodAttributes::Role::Meta::Method> role, which are the set of
563 action methods for this package.
565 =head2 $self->register_action_methods($c, @methods)
567 Creates action objects for a set of action methods using C< create_action >,
568 and registers them with the dispatcher.
570 =head2 $self->action_class(%args)
572 Used when a controller is creating an action to determine the correct base
575 =head2 $self->create_action(%args)
577 Called with a hash of data to be use for construction of a new
578 Catalyst::Action (or appropriate sub/alternative class) object.
580 =head2 $self->_application
584 Returns the application instance stored by C<new()>
588 Catalyst Contributors, see Catalyst.pm
592 This library is free software. You can redistribute it and/or modify
593 it under the same terms as Perl itself.