1Catalyst::Controller(3)User Contributed Perl DocumentatioCnatalyst::Controller(3)
2
3
4
6 Catalyst::Controller - Catalyst Controller base class
7
9 package MyApp::Controller::Search
10 use base qw/Catalyst::Controller/;
11
12 sub foo : Local {
13 my ($self,$c,@args) = @_;
14 ...
15 } # Dispatches to /search/foo
16
18 Controllers are where the actions in the Catalyst framework reside.
19 Each action is represented by a function with an attribute to identify
20 what kind of action it is. See the Catalyst::Dispatcher for more info
21 about how Catalyst dispatches to actions.
22
24 Like any other Catalyst::Component, controllers have a config hash,
25 accessible through $self->config from the controller actions. Some
26 settings are in use by the Catalyst framework:
27
28 namespace
29 This specifies the internal namespace the controller should be bound
30 to. By default the controller is bound to the URI version of the
31 controller name. For instance controller 'MyApp::Controller::Foo::Bar'
32 will be bound to 'foo/bar'. The default Root controller is an example
33 of setting namespace to '' (the null string).
34
35 path
36 Sets 'path_prefix', as described below.
37
38 action
39 Allows you to set the attributes that the dispatcher creates actions
40 out of. This allows you to do 'rails style routes', or override some
41 of the attribute definitions of actions composed from Roles. You can
42 set arguments globally (for all actions of the controller) and
43 specifically (for a single action).
44
45 __PACKAGE__->config(
46 action => {
47 '*' => { Chained => 'base', Args => 0 },
48 base => { Chained => '/', PathPart => '', CaptureArgs => 0 },
49 },
50 );
51
52 In the case above every sub in the package would be made into a Chain
53 endpoint with a URI the same as the sub name for each sub, chained to
54 the sub named "base". Ergo dispatch to "/example" would call the "base"
55 method, then the "example" method.
56
57 action_args
58 Allows you to set constructor arguments on your actions. You can set
59 arguments globally and specifically (as above). This is particularly
60 useful when using "ActionRole"s (Catalyst::Controller::ActionRole) and
61 custom "ActionClass"es.
62
63 __PACKAGE__->config(
64 action_args => {
65 '*' => { globalarg1 => 'hello', globalarg2 => 'goodbye' },
66 'specific_action' => { customarg => 'arg1' },
67 },
68 );
69
70 In the case above the action class associated with "specific_action"
71 would get passed the following arguments, in addition to the normal
72 action constructor arguments, when it is instantiated:
73
74 (globalarg1 => 'hello', globalarg2 => 'goodbye', customarg => 'arg1')
75
77 BUILDARGS ($app, @args)
78 From Catalyst::Component::ApplicationAttribute, stashes the application
79 instance as $self->_application.
80
81 $self->action_for($action_name)
82 Returns the Catalyst::Action object (if any) for a given action in this
83 controller or relative to it. You may refer to actions in controllers
84 nested under the current controllers namespace, or in controllers 'up'
85 from the current controller namespace. For example:
86
87 package MyApp::Controller::One::Two;
88 use base 'Catalyst::Controller';
89
90 sub foo :Local {
91 my ($self, $c) = @_;
92 $self->action_for('foo'); # action 'foo' in Controller 'One::Two'
93 $self->action_for('three/bar'); # action 'bar' in Controller 'One::Two::Three'
94 $self->action_for('../boo'); # action 'boo' in Controller 'One'
95 }
96
97 This returns 'undef' if there is no action matching the requested
98 action name (after any path normalization) so you should check for this
99 as needed.
100
101 $self->action_namespace($c)
102 Returns the private namespace for actions in this component. Defaults
103 to a value from the controller name (for e.g.
104 MyApp::Controller::Foo::Bar becomes "foo/bar") or can be overridden
105 from the "namespace" config key.
106
107 $self->path_prefix($c)
108 Returns the default path prefix for :PathPrefix, :Local and relative
109 :Path actions in this component. Defaults to the action_namespace or
110 can be overridden from the "path" config key.
111
112 $self->register_actions($c)
113 Finds all applicable actions for this component, creates
114 Catalyst::Action objects (using $self->create_action) for them and
115 registers them with $c->dispatcher.
116
117 $self->get_action_methods()
118 Returns a list of Moose::Meta::Method objects, doing the
119 MooseX::MethodAttributes::Role::Meta::Method role, which are the set of
120 action methods for this package.
121
122 $self->register_action_methods($c, @methods)
123 Creates action objects for a set of action methods using "
124 create_action ", and registers them with the dispatcher.
125
126 $self->action_class(%args)
127 Used when a controller is creating an action to determine the correct
128 base action class to use.
129
130 $self->create_action(%args)
131 Called with a hash of data to be use for construction of a new
132 Catalyst::Action (or appropriate sub/alternative class) object.
133
134 $self->gather_action_roles(\%action_args)
135 Gathers the list of roles to apply to an action with the given
136 %action_args.
137
138 $self->gather_default_action_roles(\%action_args)
139 returns a list of action roles to be applied based on core, builtin
140 rules. Currently only the Catalyst::ActionRole::HTTPMethods role is
141 applied this way.
142
143 $self->_application
144 $self->_app
145 Returns the application instance stored by "new()"
146
148 Please see Catalyst::Manual::Intro for more details
149
150 Think of action attributes as a sort of way to record metadata about an
151 action, similar to how annotations work in other languages you might
152 have heard of. Generally Catalyst uses these to influence how the
153 dispatcher sees your action and when it will run it in response to an
154 incoming request. They can also be used for other things. Here's a
155 summary, but you should refer to the linked manual page for additional
156 help.
157
158 Global
159 sub homepage :Global { ... }
160
161 A global action defined in any controller always runs relative to your
162 root. So the above is the same as:
163
164 sub myaction :Path("/homepage") { ... }
165
166 Absolute
167 Status: Deprecated alias to "Global".
168
169 Local
170 Alias to "Path("$action_name"). The following two actions are the
171 same:
172
173 sub myaction :Local { ... }
174 sub myaction :Path('myaction') { ... }
175
176 Relative
177 Status: Deprecated alias to "Local"
178
179 Path
180 Handle various types of paths:
181
182 package MyApp::Controller::Baz {
183
184 ...
185
186 sub myaction1 :Path { ... } # -> /baz
187 sub myaction2 :Path('foo') { ... } # -> /baz/foo
188 sub myaction2 :Path('/bar') { ... } # -> /bar
189 }
190
191 This is a general toolbox for attaching your action to a given path.
192
193 Regex
194 Regexp
195 Status: Deprecated. Use Chained methods or other techniques. If you
196 really depend on this, install the standalone
197 Catalyst::DispatchType::Regex distribution.
198
199 A global way to match a give regular expression in the incoming request
200 path.
201
202 LocalRegex
203 LocalRegexp
204 Status: Deprecated. Use Chained methods or other techniques. If you
205 really depend on this, install the standalone
206 Catalyst::DispatchType::Regex distribution.
207
208 Like "Regex" but scoped under the namespace of the containing
209 controller
210
211 Chained
212 ChainedParent
213 PathPrefix
214 PathPart
215 CaptureArgs
216 Allowed values for CaptureArgs is a single integer (CaptureArgs(2),
217 meaning two allowed) or you can declare a Moose, MooseX::Types or
218 Type::Tiny named constraint such as CaptureArgs(Int,Str) would require
219 two args with the first being a Integer and the second a string. You
220 may declare your own custom type constraints and import them into the
221 controller namespace:
222
223 package MyApp::Controller::Root;
224
225 use Moose;
226 use MooseX::MethodAttributes;
227 use MyApp::Types qw/Int/;
228
229 extends 'Catalyst::Controller';
230
231 sub chain_base :Chained(/) CaptureArgs(1) { }
232
233 sub any_priority_chain :Chained(chain_base) PathPart('') Args(1) { }
234
235 sub int_priority_chain :Chained(chain_base) PathPart('') Args(Int) { }
236
237 See Catalyst::RouteMatching for more.
238
239 Please see Catalyst::DispatchType::Chained for more.
240
241 ActionClass
242 Set the base class for the action, defaults to "Catalyst::Action". It
243 is now preferred to use "Does".
244
245 MyAction
246 Set the ActionClass using a custom Action in your project namespace.
247
248 The following is exactly the same:
249
250 sub foo_action1 : Local ActionClass('+MyApp::Action::Bar') { ... }
251 sub foo_action2 : Local MyAction('Bar') { ... }
252
253 Does
254 package MyApp::Controller::Zoo;
255
256 sub foo : Local Does('Buzz') { ... } # Catalyst::ActionRole::
257 sub bar : Local Does('~Buzz') { ... } # MyApp::ActionRole::Buzz
258 sub baz : Local Does('+MyApp::ActionRole::Buzz') { ... }
259
260 GET
261 POST
262 PUT
263 DELETE
264 OPTION
265 HEAD
266 PATCH
267 Method('...')
268 Sets the give action path to match the specified HTTP method, or via
269 one of the broadly accepted methods of overriding the 'true' method
270 (see Catalyst::ActionRole::HTTPMethods).
271
272 Args
273 When used with "Path" indicates the number of arguments expected in the
274 path. However if no Args value is set, assumed to 'slurp' all
275 remaining path pars under this namespace.
276
277 Allowed values for Args is a single integer (Args(2), meaning two
278 allowed) or you can declare a Moose, MooseX::Types or Type::Tiny named
279 constraint such as Args(Int,Str) would require two args with the first
280 being a Integer and the second a string. You may declare your own
281 custom type constraints and import them into the controller namespace:
282
283 package MyApp::Controller::Root;
284
285 use Moose;
286 use MooseX::MethodAttributes;
287 use MyApp::Types qw/Tuple Int Str StrMatch UserId/;
288
289 extends 'Catalyst::Controller';
290
291 sub user :Local Args(UserId) {
292 my ($self, $c, $int) = @_;
293 }
294
295 sub an_int :Local Args(Int) {
296 my ($self, $c, $int) = @_;
297 }
298
299 sub many_ints :Local Args(ArrayRef[Int]) {
300 my ($self, $c, @ints) = @_;
301 }
302
303 sub match :Local Args(StrMatch[qr{\d\d-\d\d-\d\d}]) {
304 my ($self, $c, $int) = @_;
305 }
306
307 If you choose not to use imported type constraints (like Type::Tiny, or
308 <MooseX::Types> you may use Moose 'stringy' types however just like
309 when you use these types in your declared attributes you must quote
310 them:
311
312 sub my_moose_type :Local Args('Int') { ... }
313
314 If you use 'reference' type constraints (such as ArrayRef[Int]) that
315 have an unknown number of allowed matches, we set this the same way
316 "Args" is. Please keep in mind that actions with an undetermined
317 number of args match at lower precedence than those with a fixed
318 number. You may use reference types such as Tuple from Types::Standard
319 that allows you to fix the number of allowed args. For example
320 Args(Tuple[Int,Int]) would be determined to be two args (or really the
321 same as Args(Int,Int).) You may find this useful for creating custom
322 subtypes with complex matching rules that you wish to reuse over many
323 actions.
324
325 See Catalyst::RouteMatching for more.
326
327 Note: It is highly recommended to use Type::Tiny for your type
328 constraints over other options. Type::Tiny exposed a better meta data
329 interface which allows us to do more and better types of introspection
330 driving tests and debugging.
331
332 Consumes('...')
333 Matches the current action against the content-type of the request.
334 Typically this is used when the request is a POST or PUT and you want
335 to restrict the submitted content type. For example, you might have an
336 HTML for that either returns classic url encoded form data, or JSON
337 when Javascript is enabled. In this case you may wish to match either
338 incoming type to one of two different actions, for properly processing.
339
340 Examples:
341
342 sub is_json : Chained('start') Consumes('application/json') { ... }
343 sub is_urlencoded : Chained('start') Consumes('application/x-www-form-urlencoded') { ... }
344 sub is_multipart : Chained('start') Consumes('multipart/form-data') { ... }
345
346 To reduce boilerplate, we include the following content type shortcuts:
347
348 Examples
349
350 sub is_json : Chained('start') Consume(JSON) { ... }
351 sub is_urlencoded : Chained('start') Consumes(UrlEncoded) { ... }
352 sub is_multipart : Chained('start') Consumes(Multipart) { ... }
353
354 You may specify more than one match:
355
356 sub is_more_than_one
357 : Chained('start')
358 : Consumes('application/x-www-form-urlencoded')
359 : Consumes('multipart/form-data')
360
361 sub is_more_than_one
362 : Chained('start')
363 : Consumes(UrlEncoded)
364 : Consumes(Multipart)
365
366 Since it is a common case the shortcut "HTMLForm" matches both
367 'application/x-www-form-urlencoded' and 'multipart/form-data'. Here's
368 the full list of available shortcuts:
369
370 JSON => 'application/json',
371 JS => 'application/javascript',
372 PERL => 'application/perl',
373 HTML => 'text/html',
374 XML => 'text/XML',
375 Plain => 'text/plain',
376 UrlEncoded => 'application/x-www-form-urlencoded',
377 Multipart => 'multipart/form-data',
378 HTMLForm => ['application/x-www-form-urlencoded','multipart/form-data'],
379
380 Please keep in mind that when dispatching, Catalyst will match the
381 first most relevant case, so if you use the "Consumes" attribute, you
382 should place your most accurate matches early in the Chain, and your
383 'catchall' actions last.
384
385 See Catalyst::ActionRole::ConsumesContent for more.
386
387 Scheme(...)
388 Allows you to specify a URI scheme for the action or action chain. For
389 example you can required that a given path be "https" or that it is a
390 websocket endpoint "ws" or "wss". For an action chain you may
391 currently only have one defined Scheme.
392
393 package MyApp::Controller::Root;
394
395 use base 'Catalyst::Controller';
396
397 sub is_http :Path(scheme) Scheme(http) Args(0) {
398 my ($self, $c) = @_;
399 $c->response->body("is_http");
400 }
401
402 sub is_https :Path(scheme) Scheme(https) Args(0) {
403 my ($self, $c) = @_;
404 $c->response->body("is_https");
405 }
406
407 In the above example http://localhost/root/scheme would match the first
408 action (is_http) but https://localhost/root/scheme would match the
409 second.
410
411 As an added benefit, if an action or action chain defines a Scheme,
412 when using $c->uri_for the scheme of the generated URL will use what
413 you define in the action or action chain (the current behavior is to
414 set the scheme based on the current incoming request). This makes it
415 easier to use uri_for on websites where some paths are secure and
416 others are not. You may also use this to other schemes like
417 websockets.
418
419 See Catalyst::ActionRole::Scheme for more.
420
422 _parse_[$name]_attr
423 Allows you to customize parsing of subroutine attributes.
424
425 sub myaction1 :Path TwoArgs { ... }
426
427 sub _parse_TwoArgs_attr {
428 my ( $self, $c, $name, $value ) = @_;
429 # $self -> controller instance
430 #
431 return(Args => 2);
432 }
433
434 Please note that this feature does not let you actually assign new
435 functions to actions via subroutine attributes, but is really more for
436 creating useful aliases to existing core and extended attributes, and
437 transforms based on existing information (like from configuration).
438 Code for actually doing something meaningful with the subroutine
439 attributes will be located in the Catalyst::Action classes (or your
440 subclasses), Catalyst::Dispatcher and in subclasses of
441 Catalyst::DispatchType. Remember these methods only get called
442 basically once when the application is starting, not per request!
443
445 Catalyst Contributors, see Catalyst.pm
446
448 This library is free software. You can redistribute it and/or modify it
449 under the same terms as Perl itself.
450
451
452
453perl v5.30.1 2020-01-29 Catalyst::Controller(3)