1Maypole(3) User Contributed Perl Documentation Maypole(3)
2
3
4
6 Maypole - MVC web application framework
7
9 The canonical example used in the Maypole documentation is the beer
10 database:
11
12 package BeerDB;
13 use strict;
14 use warnings;
15
16 # choose a frontend, initialise the config object, and load a plugin
17 use Maypole::Application qw/Relationship/;
18
19 # set everything up
20 __PACKAGE__->setup("dbi:SQLite:t/beerdb.db");
21
22 # get the empty config object created by Maypole::Application
23 my $config = __PACKAGE__->config;
24
25 # basic settings
26 $config->uri_base("http://localhost/beerdb");
27 $config->template_root("/path/to/templates");
28 $config->rows_per_page(10);
29 $config->display_tables([qw/beer brewery pub style/]);
30
31 # table relationships
32 $config->relationships([
33 "a brewery produces beers",
34 "a style defines beers",
35 "a pub has beers on handpumps",
36 ]);
37
38 # validation
39 BeerDB::Brewery->untaint_columns( printable => [qw/name notes url/] );
40 BeerDB::Pub->untaint_columns( printable => [qw/name notes url/] );
41 BeerDB::Style->untaint_columns( printable => [qw/name notes/] );
42 BeerDB::Beer->untaint_columns(
43 printable => [qw/abv name price notes/],
44 integer => [qw/style brewery score/],
45 date => [ qw/date/],
46 );
47
48 # note : set up model before calling this method
49 BeerDB::Beer->required_columns([qw/name/]);
50
51 1;
52
54 This documents the Maypole request object. See the Maypole::Manual, for
55 a detailed guide to using Maypole.
56
57 Maypole is a Perl web application framework similar to Java's struts.
58 It is essentially completely abstracted, and so doesn't know anything
59 about how to talk to the outside world.
60
61 To use it, you need to create a driver package which represents your
62 entire application. This is the "BeerDB" package used as an example in
63 the manual.
64
65 This needs to first use Maypole::Application which will make your
66 package inherit from the appropriate platform driver such as
67 "Apache::MVC" or "CGI::Maypole". Then, the driver calls "setup". This
68 sets up the model classes and configures your application. The default
69 model class for Maypole uses Class::DBI to map a database to classes,
70 but this can be changed by altering configuration (before calling
71 setup.)
72
74 Note that some details in some of these resources may be out of date.
75
76 The Maypole Manual
77 The primary documentation is the Maypole manual. This lives in the
78 "Maypole::Manual" pod documents included with the distribution.
79
80 Embedded POD
81 Individual packages within the distribution contain (more or less)
82 detailed reference documentation for their API.
83
84 Mailing lists
85 There are two mailing lists - maypole-devel and maypole-users - see
86 http://maypole.perl.org/?MailingList
87
88 The Maypole Wiki
89 The Maypole wiki provides a useful store of extra documentation -
90 http://maypole.perl.org
91
92 In particular, there's a FAQ (http://maypole.perl.org/?FAQ) and a
93 cookbook (http://maypole.perl.org/?Cookbook). Again, certain
94 information on these pages may be out of date.
95
96 Web applications with Maypole
97 A tutorial written by Simon Cozens for YAPC::EU 2005 -
98 http://www.aarontrevena.co.uk/opensource/maypole/maypole-tutorial.pdf
99 [228KB].
100
101 A Database-Driven Web Application in 18 Lines of Code
102 By Paul Barry, published in Linux Journal, March 2005.
103
104 http://www.linuxjournal.com/article/7937
105
106 "From zero to Web-based database application in eight easy steps".
107
108 Maypole won a 2005 Linux Journal Editor's Choice Award
109 (http://www.linuxjournal.com/article/8293) after featuring in this
110 article.
111
112 Build Web apps with Maypole
113 By Simon Cozens, on IBM's DeveloperWorks website, May 2004.
114
115 http://www-128.ibm.com/developerworks/linux/library/l-maypole/
116
117 Rapid Web Application Deployment with Maypole
118 By Simon Cozens, on O'Reilly's Perl website, April 2004.
119
120 http://www.perl.com/pub/a/2004/04/15/maypole.html
121
122 Authentication
123 Some notes written by Simon Cozens. A little bit out of date, but
124 still very useful:
125 http://www.aarontrevena.co.uk/opensource/maypole/authentication.html
126
127 CheatSheet
128 There's a refcard for the Maypole (and Class::DBI) APIs on the wiki
129 - http://maypole.perl.org/?CheatSheet. Probably a little out of
130 date now - it's a wiki, so feel free to fix any errors!
131
132 Plugins and add-ons
133 There are a large and growing number of plugins and other add-on
134 modules available on CPAN -
135 http://search.cpan.org/search?query=maypole&mode=module
136
137 del.icio.us
138 You can find a range of useful Maypole links, particularly to
139 several thoughtful blog entries, starting here:
140 http://del.icio.us/search/?all=maypole
141
142 CPAN ratings
143 There are a couple of short reviews here:
144 http://cpanratings.perl.org/dist/Maypole
145
147 As a framework, Maypole provides a number of hooks - methods that are
148 intended to be overridden. Some of these methods come with useful
149 default behaviour, others do nothing by default. Hooks include:
150
151 Class methods
152 -------------
153 debug
154 setup
155 setup_model
156 load_model_subclass
157 init
158
159 Instance methods
160 ----------------
161 start_request_hook
162 is_model_applicable
163 get_session
164 authenticate
165 exception
166 additional_data
167 preprocess_path
168
170 debug
171 sub My::App::debug {1}
172
173 Returns the debugging flag. Override this in your application class
174 to enable/disable debugging.
175
176 You can also set the "debug" flag via Maypole::Application.
177
178 Some packages respond to higher debug levels, try increasing it to
179 2 or 3.
180
181 config
182 Returns the Maypole::Config object
183
184 setup
185 My::App->setup($data_source, $user, $password, \%attr);
186
187 Initialise the Maypole application and plugins and model classes.
188 Your application should call this after setting up configuration
189 data via "config".
190
191 It calls the hook "setup_model" to setup the model. The %attr hash
192 contains options and arguments used to set up the model. See the
193 particular model's documentation. However here is the most usage of
194 setup where Maypole::Model::CDBI is the base class.
195
196 My::App->setup($data_source, $user, $password,
197 { options => { # These are DB connection options
198 AutoCommit => 0,
199 RaiseError => 1,
200 ...
201 },
202 # These are Class::DBI::Loader arguments.
203 relationships => 1,
204 ...
205 }
206 );
207
208 Also, see Maypole::Manual::Plugins.
209
210 setup_model
211 Called by "setup". This method builds the Maypole model hierarchy.
212
213 A likely target for over-riding, if you need to build a customised
214 model.
215
216 This method also ensures any code in custom model classes is
217 loaded, so you don't need to load them in the driver.
218
219 load_model_subclass($subclass)
220 This method is called from "setup_model()". It attempts to load the
221 $subclass package, if one exists. So if you make a customized
222 "BeerDB::Beer" package, you don't need to explicitly load it.
223
224 If automatic loading causes problems, Override load_model_subclass
225 in your driver.
226
227 sub load_model_subclass {};
228
229 Or perhaps during development, if you don't want to load up custom
230 classes, you can override this method and load them manually.
231
232 init
233 Loads the view class and instantiates the view object.
234
235 You should not call this directly, but you may wish to override
236 this to add application-specific initialisation - see
237 Maypole::Manual::Plugins.
238
239 new Constructs a very minimal new Maypole request object.
240
241 view_object
242 Get/set the Maypole::View object
243
245 Workflow
246 handler
247 This method sets up the class if it's not done yet, sets some
248 defaults and leaves the dirty work to "handler_guts".
249
250 component
251 Run Maypole sub-requests as a component of the request
252
253 [% request.component("/beer/view_as_component/20") %]
254
255 Allows you to integrate the results of a Maypole request into an existing
256 request. You'll need to set up actions and templates
257 which return fragments of HTML rather than entire pages, but once you've
258 done that, you can use the C<component> method of the Maypole request object
259 to call those actions. You may pass a query string in the usual URL style.
260
261 You should not fully qualify the Maypole URLs.
262
263 Note: any HTTP POST or URL parameters passed to the parent are not
264 passed to the component sub-request, only what is included in the
265 url passed as an argument to the method
266
267 handler_guts
268 This is the main request handling method and calls various methods
269 to handle the request/response and defines the workflow within
270 Maypole.
271
272 warn
273 $r->warn('its all gone pete tong');
274
275 Warn must be implemented by the backend, i.e. Apache::MVC and warn
276 to stderr or appropriate logfile.
277
278 You can also over-ride this in your Maypole driver, should you want
279 to use something like Log::Log4perl instead.
280
281 build_form_elements
282 $r->build_form_elements(0);
283
284 Specify (in an action) whether to build HTML form elements and
285 populate the cgi element of classmetadata in the view.
286
287 You can set this globally using the accessor of the same name in
288 Maypole::Config, this method allows you to over-ride that setting
289 per action.
290
291 get_request
292 You should only need to define this method if you are writing a new
293 Maypole backend. It should return something that looks like an
294 Apache or CGI request object, it defaults to blank.
295
296 parse_location
297 Turns the backend request (e.g. Apache::MVC, Maypole, CGI) into a
298 Maypole request. It does this by setting the "path", and invoking
299 "parse_path" and "parse_args".
300
301 You should only need to define this method if you are writing a new
302 Maypole backend.
303
304 start_request_hook
305 This is called immediately after setting up the basic request. The
306 default method does nothing.
307
308 The value of "$r->status" is set to "OK" before this hook is run.
309 Your implementation can change the status code, or leave it alone.
310
311 After this hook has run, Maypole will check the value of "status".
312 For any value other than "OK", Maypole returns the "status"
313 immediately.
314
315 This is useful for filtering out requests for static files, e.g.
316 images, which should not be processed by Maypole or by the
317 templating engine:
318
319 sub start_request_hook
320 {
321 my ($r) = @_;
322
323 $r->status(DECLINED) if $r->path =~ /\.jpg$/;
324 }
325
326 Multiple plugins, and the driver, can define this hook - Maypole
327 will call all of them. You should check for and probably not change
328 any non-OK "status" value:
329
330 package Maypole::Plugin::MyApp::SkipFavicon;
331
332 sub start_request_hook
333 {
334 my ($r) = @_;
335
336 # check if a previous plugin has already DECLINED this request
337 # - probably unnecessary in this example, but you get the idea
338 return unless $r->status == OK;
339
340 # then do our stuff
341 $r->status(DECLINED) if $r->path =~ /favicon\.ico/;
342 }
343
344 is_applicable
345 This method is deprecated as of version 2.11. If you have
346 overridden it, please override "is_model_applicable" instead, and
347 change the return type from a Maypole:Constant to a true/false
348 value.
349
350 Returns a Maypole::Constant to indicate whether the request is
351 valid.
352
353 is_model_applicable
354 Returns true or false to indicate whether the request is valid.
355
356 The default implementation checks that "$r->table" is publicly
357 accessible and that the model class is configured to handle the
358 "$r->action".
359
360 get_session
361 Called immediately after "start_request_hook()".
362
363 This method should return a session, which will be stored in the
364 request's "session" attribute.
365
366 The default method is empty.
367
368 get_user
369 Called immediately after "get_session".
370
371 This method should return a user, which will be stored in the
372 request's "user" attribute.
373
374 The default method is empty.
375
376 call_authenticate
377 This method first checks if the relevant model class can
378 authenticate the user, or falls back to the default authenticate
379 method of your Maypole application.
380
381 authenticate
382 Returns a Maypole::Constant to indicate whether the user is
383 authenticated for the Maypole request.
384
385 The default implementation returns "OK"
386
387 call_exception
388 This model is called to catch exceptions, first after authenticate,
389 then after processing the model class, and finally to check for
390 exceptions from the view class.
391
392 This method first checks if the relevant model class can handle
393 exceptions the user, or falls back to the default exception method
394 of your Maypole application.
395
396 exception
397 This method is called if any exceptions are raised during the
398 authentication or model/view processing. It should accept the
399 exception as a parameter and return a Maypole::Constant to indicate
400 whether the request should continue to be processed.
401
402 additional_data
403 Called before the model processes the request, this method gives
404 you a chance to do some processing for each request, for example,
405 manipulating "template_args".
406
407 send_output
408 Sends the output and additional headers to the user.
409
410 Path processing and manipulation
411 path
412 Returns the request path
413
414 parse_path
415 Parses the request path and sets the "args", "action" and "table"
416 properties. Calls "preprocess_path" before parsing path and setting
417 properties.
418
419 preprocess_path
420 Sometimes when you don't want to rewrite or over-ride parse_path
421 but want to rewrite urls or extract data from them before it is
422 parsed, the preprocess_path/location methods allow you to munge
423 paths and urls before maypole maps them to actions, classes, etc.
424
425 This method is called after parse_location has populated the
426 request information and before parse_path has populated the model
427 and action information, and is passed the request object.
428
429 You can set action, args or table in this method and parse_path
430 will then leave those values in place or populate them based on the
431 current value of the path attribute if they are not present.
432
433 preprocess_location
434 This method is called at the start of parse_location, after the
435 headers in, and allows you to rewrite the url used by maypole, or
436 dynamically set configuration like the base_uri based on the
437 hostname or path.
438
439 make_path( %args or \%args or @args )
440 This is the counterpart to "parse_path". It generates a path to use
441 in links, form actions etc. To implement your own path scheme, just
442 override this method and "parse_path".
443
444 %args = ( table => $table,
445 action => $action,
446 additional => $additional, # optional - generally an object ID
447 );
448
449 \%args = as above, but a ref
450
451 @args = ( $table, $action, $additional ); # $additional is optional
452
453 "id" can be used as an alternative key to "additional".
454
455 $additional can be a string, an arrayref, or a hashref. An arrayref
456 is expanded into extra path elements, whereas a hashref is
457 translated into a query string.
458
459 make_uri( @segments )
460 Make a URI object given table, action etc. Automatically adds the
461 "uri_base".
462
463 If the final element in @segments is a hash ref, "make_uri" will
464 render it as a query string.
465
466 parse_args
467 Turns post data and query string paramaters into a hash of
468 "params".
469
470 You should only need to define this method if you are writing a new
471 Maypole backend.
472
473 get_template_root
474 Implementation-specific path to template root.
475
476 You should only need to define this method if you are writing a new
477 Maypole backend. Otherwise, see "template_root" in Maypole::Config
478
479 Request properties
480 model_class
481 Returns the perl package name that will serve as the model for the
482 request. It corresponds to the request "table" attribute.
483
484 objects
485 Get/set a list of model objects. The objects will be accessible in
486 the view templates.
487
488 If the first item in "$self->args" can be "retrieve()"d by the
489 model class, it will be removed from "args" and the retrieved
490 object will be added to the "objects" list. See Maypole::Model for
491 more information.
492
493 object
494 Alias to get/set the first/only model object. The object will be
495 accessible in the view templates.
496
497 When used to set the object, will overwrite the request objects
498 with a single object.
499
500 template_args
501 $self->template_args->{foo} = 'bar';
502
503 Get/set a hash of template variables.
504
505 Maypole reserved words for template variables will over-ride values
506 in template_variables.
507
508 Reserved words are : r, request, object, objects, base, config and
509 errors, as well as the current class or object name.
510
511 stash
512 A place to put custom application data. Not used by Maypole itself.
513
514 template
515 Get/set the template to be used by the view. By default, it returns
516 "$self->action"
517
518 error
519 Get/set a request error
520
521 output
522 Get/set the response output. This is usually populated by the view
523 class. You can skip view processing by setting the "output".
524
525 table
526 The table part of the Maypole request path
527
528 action
529 The action part of the Maypole request path
530
531 args
532 A list of remaining parts of the request path after table and
533 action have been removed
534
535 headers_in
536 A Maypole::Headers object containing HTTP headers for the request
537
538 headers_out
539 A HTTP::Headers object that contains HTTP headers for the output
540
541 document_encoding
542 Get/set the output encoding. Default: utf-8.
543
544 content_type
545 Get/set the output content type. Default: text/html
546
547 get_protocol
548 Returns the protocol the request was made with, i.e. https
549
550 Request parameters
551 The source of the parameters may vary depending on the Maypole backend,
552 but they are usually populated from request query string and POST data.
553
554 Maypole supplies several approaches for accessing the request
555 parameters. Note that the current implementation (via a hashref) of
556 "query" and "params" is likely to change in a future version of
557 Maypole. So avoid direct access to these hashrefs:
558
559 $r->{params}->{foo} # bad
560 $r->params->{foo} # better
561
562 $r->{query}->{foo} # bad
563 $r->query->{foo} # better
564
565 $r->param('foo') # best
566
567 param
568 An accessor (get or set) for request parameters. It behaves
569 similarly to CGI::param() for accessing CGI parameters, i.e.
570
571 $r->param # returns list of keys
572 $r->param($key) # returns value for $key
573 $r->param($key => $value) # returns old value, sets to new value
574
575 params
576 Returns a hashref of request parameters.
577
578 Note: Where muliple values of a parameter were supplied, the
579 "params" value will be an array reference.
580
581 query
582 Alias for "params".
583
584 Utility methods
585
586 redirect_request
587 Sets output headers to redirect based on the arguments provided
588
589 Accepts either a single argument of the full url to redirect to, or
590 a hash of named parameters :
591
592 $r->redirect_request('http://www.example.com/path');
593
594 or
595
596 $r->redirect_request(protocol=>'https', domain=>'www.example.com',
597 path=>'/path/file?arguments', status=>'302', url=>'..');
598
599 The named parameters are protocol, domain, path, status and url
600
601 Only 1 named parameter is required but other than url, they can be
602 combined as required and current values (from the request) will be
603 used in place of any missing arguments. The url argument must be a
604 full url including protocol and can only be combined with status.
605
606 make_random_id
607 returns a unique id for this request can be used to prevent or
608 detect repeat submissions.
609
611 See Maypole::Manual::Workflow for a detailed discussion of the sequence
612 of calls during processing of a request. This is a brief summary:
613
614 INITIALIZATION
615 Model e.g.
616 BeerDB Maypole::Model::CDBI
617 | |
618 setup | |
619 o-------->|| |
620 || setup_model | setup_database() creates
621 ||------+ | a subclass of the Model
622 |||<----+ | for each table
623 ||| | |
624 ||| setup_database | |
625 |||--------------------->|| 'create' *
626 ||| ||----------> $subclass
627 ||| | |
628 ||| load_model_subclass | |
629 foreach |||------+ ($subclass) | |
630 $subclass ||||<----+ | require |
631 ||||--------------------------------------->|
632 ||| | |
633 ||| adopt($subclass) | |
634 |||--------------------->|| |
635 | | |
636 | | |
637 |-----+ init | |
638 ||<---+ | |
639 || | new | view_object: e.g.
640 ||---------------------------------------------> Maypole::View::TT
641 | | | |
642 | | | |
643 | | | |
644 | | | |
645 | | | |
646
647
648
649 HANDLING A REQUEST
650
651
652 BeerDB Model $subclass view_object
653 | | | |
654 handler | | | |
655 o-------->| new | | |
656 |-----> r:BeerDB | | |
657 | | | | |
658 | | | | |
659 | || | | |
660 | ||-----+ parse_location | | |
661 | |||<---+ | | |
662 | || | | |
663 | ||-----+ start_request_hook | | |
664 | |||<---+ | | |
665 | || | | |
666 | ||-----+ get_session | | |
667 | |||<---+ | | |
668 | || | | |
669 | ||-----+ get_user | | |
670 | |||<---+ | | |
671 | || | | |
672 | ||-----+ handler_guts | | |
673 | |||<---+ | | |
674 | ||| class_of($table) | | |
675 | |||------------------------->|| | |
676 | ||| $subclass || | |
677 | |||<-------------------------|| | |
678 | ||| | | |
679 | |||-----+ is_model_applicable| | |
680 | ||||<---+ | | |
681 | ||| | | |
682 | |||-----+ call_authenticate | | |
683 | ||||<---+ | | |
684 | ||| | | |
685 | |||-----+ additional_data | | |
686 | ||||<---+ | | |
687 | ||| process | | |
688 | |||--------------------------------->|| fetch_objects
689 | ||| | ||-----+ |
690 | ||| | |||<---+ |
691 | ||| | || |
692 | ||| | || $action
693 | ||| | ||-----+ |
694 | ||| | |||<---+ |
695 | ||| process | | |
696 | |||------------------------------------------->|| template
697 | ||| | | ||-----+
698 | ||| | | |||<---+
699 | ||| | | |
700 | || send_output | | |
701 | ||-----+ | | |
702 | |||<---+ | | |
703 $status | || | | |
704 <------------------|| | | |
705 | | | | |
706 | X | | |
707 | | | |
708 | | | |
709 | | | |
710
712 There's more documentation, examples, and information on our mailing
713 lists at the Maypole web site:
714
715 <http://maypole.perl.org/>
716
717 Maypole::Application, Apache::MVC, CGI::Maypole.
718
720 Maypole is currently maintained by Aaron Trevena.
721
723 Simon Cozens, "simon#cpan.org"
724
725 Simon Flack maintained Maypole from 2.05 to 2.09
726
727 Sebastian Riedel, "sri#oook.de" maintained Maypole from 1.99_01 to 2.04
728
730 Sebastian Riedel, Danijel Milicevic, Dave Slack, Jesse Sheidlower, Jody
731 Belka, Marcus Ramberg, Mickael Joanne, Randal Schwartz, Simon Flack,
732 Steve Simms, Veljko Vidovic and all the others who've helped.
733
735 You may distribute this code under the same terms as Perl itself.
736
737
738
739perl v5.30.1 2020-01-30 Maypole(3)