]> git.decadent.org.uk Git - maypole.git/blob - lib/Maypole.pm
Refactored handler_guts - put view processing in a separate
[maypole.git] / lib / Maypole.pm
1 package Maypole;
2 use base qw(Class::Accessor::Fast Class::Data::Inheritable);
3 use UNIVERSAL::require;
4 use strict;
5 use warnings;
6 use Maypole::Config;
7 use Maypole::Constants;
8 use Maypole::Headers;
9
10 our $VERSION = '2.10';
11
12 # proposed privacy conventions:
13 # - no leading underscore     - public to custom application code and plugins
14 # - single leading underscore - private to the main Maypole stack - *not* including plugins
15 # - double leading underscore - private to the current package
16
17 __PACKAGE__->mk_classdata($_) for qw( config init_done view_object );
18 __PACKAGE__->mk_accessors(
19     qw( params query objects model_class template_args output path
20         args action template error document_encoding content_type table
21         headers_in headers_out )
22 );
23 __PACKAGE__->config( Maypole::Config->new() );
24 __PACKAGE__->init_done(0);
25
26 sub debug { 0 }
27
28 sub setup 
29 {
30     my $calling_class = shift;
31     
32     $calling_class = ref $calling_class if ref $calling_class;
33     
34     my $config = $calling_class->config;
35     
36     $config->model || $config->model('Maypole::Model::CDBI');
37     
38     $config->model->require or die 
39         "Couldn't load the model class $config->{model}: $@";
40     
41     $config->model->setup_database($config, $calling_class, @_);
42     
43     foreach my $subclass ( @{ $config->classes } ) 
44     {
45         no strict 'refs';
46         unshift @{ $subclass . "::ISA" }, $config->model;
47         $config->model->adopt($subclass)
48           if $config->model->can("adopt");
49     }
50 }
51
52 sub init 
53 {
54     my $class  = shift;
55     my $config = $class->config;
56     $config->view || $config->view("Maypole::View::TT");
57     $config->view->require;
58     die "Couldn't load the view class " . $config->view . ": $@" if $@;
59     $config->display_tables
60       || $config->display_tables( $class->config->tables );
61     $class->view_object( $class->config->view->new );
62     $class->init_done(1);
63
64 }
65
66 # handler() has a method attribute so that mod_perl will invoke
67 # BeerDB->handler() as a method rather than a plain function
68 # BeerDB::handler() and so this inherited implementation will be
69 # found. See e.g. "Practical mod_perl"  by Bekman & Cholet for
70 # more information <http://modperlbook.org/html/ch25_01.html>
71 sub handler : method 
72 {
73     # See Maypole::Workflow before trying to understand this.
74     my ($class, $req) = @_;
75     
76     $class->init unless $class->init_done;
77
78     # Create the request object
79     my $r = bless {
80         template_args => {},
81         config        => $class->config
82     }, $class;
83     
84     $r->headers_out(Maypole::Headers->new);
85     
86     $r->get_request($req);
87     
88     $r->parse_location();
89     
90     my $status = $r->handler_guts();
91     
92     return $status unless $status == OK;
93     
94     $r->send_output;
95     
96     return $status;
97 }
98
99 # The root of all evil
100 sub handler_guts 
101 {
102     my ($r) = @_;
103     
104     $r->__load_model;
105
106     my $applicable = $r->is_applicable;
107     
108     unless ( $applicable == OK ) 
109     {
110         # It's just a plain template
111         $r->model_class(undef);
112         
113         my $path = $r->path;
114         $path =~ s{/$}{};    # De-absolutify
115         $r->path($path);
116         
117         $r->template($r->path);
118     }
119
120     # We authenticate every request, needed for proper session management
121     my $status;
122     
123     eval { $status = $r->call_authenticate };
124     
125     if ( my $error = $@ ) 
126     {
127         $status = $r->call_exception($error);
128         
129         if ( $status != OK ) 
130         {
131             warn "caught authenticate error: $error";
132             return $r->debug ? $r->view_object->error($r, $error) : ERROR;
133         }
134     }
135     
136     if ( $r->debug and $status != OK and $status != DECLINED ) 
137     {
138         $r->view_object->error( $r,
139             "Got unexpected status $status from calling authentication" );
140     }
141     
142     return $status unless $status == OK;
143
144     # We run additional_data for every request
145     $r->additional_data;
146     
147     if ( $applicable == OK ) 
148     {
149         eval { $r->model_class->process($r) };
150         
151         if ( my $error = $@ ) 
152         {
153             $status = $r->call_exception($error);
154             if ( $status != OK ) 
155             {
156                 warn "caught model error: $error";
157                 return $r->debug ? $r->view_object->error($r, $error) : ERROR;
158             }
159         }
160     }
161     
162     # unusual path - perhaps output has been set to an error message
163     return OK if $r->output;
164     
165     # normal path - no output has been generated yet
166     return $r->__call_process_view;
167 }
168
169 sub __call_process_view
170 {
171     my ($r) = @_;
172     
173     my $status;
174     
175     eval { $status = $r->view_object->process($r) };
176     
177     if ( my $error = $@ ) 
178     {
179         $status = $r->call_exception($error);
180         
181         if ( $status != OK ) 
182         {
183             warn "caught view error: $error" if $r->debug;
184             return $r->debug ? $r->view_object->error($r, $error) : ERROR;
185         }
186     }
187     
188     return $status;
189 }
190
191 sub __load_model
192 {
193     my ($r) = @_;
194     $r->model_class( $r->config->model->class_of($r, $r->table) );
195 }
196
197 sub is_applicable {
198     my $self   = shift;
199     my $config = $self->config;
200     $config->ok_tables || $config->ok_tables( $config->display_tables );
201     $config->ok_tables( { map { $_ => 1 } @{ $config->ok_tables } } )
202       if ref $config->ok_tables eq "ARRAY";
203     warn "We don't have that table ($self->{table}).\n"
204       . "Available tables are: "
205       . join( ",", @{ $config->{display_tables} } )
206       if $self->debug
207       and not $config->ok_tables->{ $self->{table} }
208       and $self->{action};
209     return DECLINED() unless exists $config->ok_tables->{ $self->{table} };
210
211     # Is it public?
212     return DECLINED unless $self->model_class->is_public( $self->{action} );
213     return OK();
214 }
215
216 sub call_authenticate {
217     my $self = shift;
218
219     # Check if we have a model class
220     if ( $self->{model_class} ) {
221         return $self->model_class->authenticate($self)
222           if $self->model_class->can("authenticate");
223     }
224     return $self->authenticate($self);   # Interface consistency is a Good Thing
225 }
226
227 sub call_exception {
228     my $self = shift;
229     my ($error) = @_;
230
231     # Check if we have a model class
232     if (   $self->{model_class}
233         && $self->model_class->can('exception') )
234     {
235         my $status = $self->model_class->exception( $self, $error );
236         return $status if $status == OK;
237     }
238     return $self->exception($error);
239 }
240
241 sub additional_data { }
242
243 sub authenticate { return OK }
244
245 sub exception { return ERROR }
246
247 sub parse_path {
248     my $self = shift;
249     $self->{path} ||= "frontpage";
250     my @pi = $self->{path} =~ m{([^/]+)/?}g;
251     $self->{table}  = shift @pi;
252     $self->{action} = shift @pi;
253     $self->{action} ||= "index";
254     $self->{args}   = \@pi;
255 }
256
257 sub param { # like CGI::param(), but read-only
258     my $r = shift;
259     my ($key) = @_;
260     if (defined $key) {
261         unless (exists $r->{params}{$key}) {
262             return wantarray() ? () : undef;
263         }
264         my $val = $r->{params}{$key};
265         if (wantarray()) {
266             return ref $val ? @$val : $val;
267         } else {
268             return ref $val ? $val->[0] : $val;
269         }
270     } else {
271         return keys %{$r->{params}};
272     }
273 }
274
275 sub get_template_root { "." }
276 sub get_request       { }
277
278 sub parse_location {
279     die "Do not use Maypole directly; use Apache::MVC or similar";
280 }
281
282 sub send_output {
283     die "Do not use Maypole directly; use Apache::MVC or similar";
284 }
285
286 # Session and Repeat Submission Handling
287
288 sub make_random_id {
289     use Maypole::Session;
290     return Maypole::Session::generate_unique_id();
291 }
292
293 =head1 NAME
294
295 Maypole - MVC web application framework
296
297 =head1 SYNOPSIS
298
299 See L<Maypole::Application>.
300
301 =head1 DESCRIPTION
302
303 This documents the Maypole request object. See the L<Maypole::Manual>, for a
304 detailed guide to using Maypole.
305
306 Maypole is a Perl web application framework similar to Java's struts. It is 
307 essentially completely abstracted, and so doesn't know anything about
308 how to talk to the outside world.
309
310 To use it, you need to create a package which represents your entire
311 application. In our example above, this is the C<BeerDB> package.
312
313 This needs to first use L<Maypole::Application> which will make your package
314 inherit from the appropriate platform driver such as C<Apache::MVC> or
315 C<CGI::Maypole>, and then call setup.  This sets up the model classes and
316 configures your application. The default model class for Maypole uses
317 L<Class::DBI> to map a database to classes, but this can be changed by altering
318 configuration. (B<Before> calling setup.)
319
320 =head2 CLASS METHODS
321
322 =head3 config
323
324 Returns the L<Maypole::Config> object
325
326 =head3 setup
327
328     My::App->setup($data_source, $user, $password, \%attr);
329
330 Initialise the maypole application and model classes. Your application should
331 call this after setting configuration via L<"config">
332
333 =head3 init
334
335 You should not call this directly, but you may wish to override this to
336 add
337 application-specific initialisation.
338
339 =head3 view_object
340
341 Get/set the Maypole::View object
342
343 =head3 debug
344
345     sub My::App::debug {1}
346
347 Returns the debugging flag. Override this in your application class to
348 enable/disable debugging.
349
350 =head2 INSTANCE METHODS
351
352 =head3 parse_location
353
354 Turns the backend request (e.g. Apache::MVC, Maypole, CGI) into a
355 Maypole
356 request. It does this by setting the C<path>, and invoking C<parse_path>
357 and
358 C<parse_args>.
359
360 You should only need to define this method if you are writing a new
361 Maypole
362 backend.
363
364 =head3 path
365
366 Returns the request path
367
368 =head3 parse_path
369
370 Parses the request path and sets the C<args>, C<action> and C<table> 
371 properties
372
373 =head3 table
374
375 The table part of the Maypole request path
376
377 =head3 action
378
379 The action part of the Maypole request path
380
381 =head3 args
382
383 A list of remaining parts of the request path after table and action
384 have been
385 removed
386
387 =head3 headers_in
388
389 A L<Maypole::Headers> object containing HTTP headers for the request
390
391 =head3 headers_out
392
393 A L<HTTP::Headers> object that contains HTTP headers for the output
394
395 =head3 parse_args
396
397 Turns post data and query string paramaters into a hash of C<params>.
398
399 You should only need to define this method if you are writing a new
400 Maypole
401 backend.
402
403 =head3 param
404
405 An accessor for request parameters. It behaves similarly to CGI::param() for
406 accessing CGI parameters.
407
408 =head3 params
409
410 Returns a hash of request parameters. The source of the parameters may vary
411 depending on the Maypole backend, but they are usually populated from request
412 query string and POST data.
413
414 B<Note:> Where muliple values of a parameter were supplied, the
415 C<params> 
416 value
417 will be an array reference.
418
419 =head3 get_template_root
420
421 Implementation-specific path to template root.
422
423 You should only need to define this method if you are writing a new
424 Maypole
425 backend. Otherwise, see L<Maypole::Config/"template_root">
426
427 =head3 get_request
428
429 You should only need to define this method if you are writing a new
430 Maypole backend. It should return something that looks like an Apache
431 or CGI request object, it defaults to blank.
432
433
434 =head3 is_applicable
435
436 Returns a Maypole::Constant to indicate whether the request is valid.
437
438 The default implementation checks that C<$r-E<gt>table> is publicly
439 accessible
440 and that the model class is configured to handle the C<$r-E<gt>action>
441
442 =head3 authenticate
443
444 Returns a Maypole::Constant to indicate whether the user is
445 authenticated for
446 the Maypole request.
447
448 The default implementation returns C<OK>
449
450 =head3 model_class
451
452 Returns the perl package name that will serve as the model for the
453 request. It corresponds to the request C<table> attribute.
454
455 =head3 additional_data
456
457 Called before the model processes the request, this method gives you a
458 chance
459 to do some processing for each request, for example, manipulating
460 C<template_args>.
461
462 =head3 objects
463
464 Get/set a list of model objects. The objects will be accessible in the
465 view
466 templates.
467
468 If the first item in C<$r-E<gt>args> can be C<retrieve()>d by the model
469 class,
470 it will be removed from C<args> and the retrieved object will be added
471 to the
472 C<objects> list. See L<Maypole::Model> for more information.
473
474 =head3 template_args
475
476     $r->template_args->{foo} = 'bar';
477
478 Get/set a hash of template variables.
479
480 =head3 template
481
482 Get/set the template to be used by the view. By default, it returns
483 C<$r-E<gt>action>
484
485 =head3 exception
486
487 This method is called if any exceptions are raised during the
488 authentication 
489 or
490 model/view processing. It should accept the exception as a parameter and 
491 return
492 a Maypole::Constant to indicate whether the request should continue to
493 be
494 processed.
495
496 =head3 error
497
498 Get/set a request error
499
500 =head3 output
501
502 Get/set the response output. This is usually populated by the view
503 class. You
504 can skip view processing by setting the C<output>.
505
506 =head3 document_encoding
507
508 Get/set the output encoding. Default: utf-8.
509
510 =head3 content_type
511
512 Get/set the output content type. Default: text/html
513
514 =head3 send_output
515
516 Sends the output and additional headers to the user.
517
518 =head3 call_authenticate
519
520 This method first checks if the relevant model class
521 can authenticate the user, or falls back to the default
522 authenticate method of your Maypole application.
523
524
525 =head3 call_exception
526
527 This model is called to catch exceptions, first after authenticate, then after
528 processing the model class, and finally to check for exceptions from the view
529 class.
530
531 This method first checks if the relevant model class
532 can handle exceptions the user, or falls back to the default
533 exception method of your Maypole application.
534
535 =head3 make_random_id
536
537 returns a unique id for this request can be used to prevent or detect repeat submissions.
538
539 =head3 handler
540
541 This method sets up the class if it's not done yet, sets some
542 defaults and leaves the dirty work to handler_guts.
543
544 =head3 handler_guts
545
546 This is the core of maypole. You don't want to know.
547
548 =head1 SEE ALSO
549
550 There's more documentation, examples, and a information on our mailing lists
551 at the Maypole web site:
552
553 L<http://maypole.perl.org/>
554
555 L<Maypole::Application>, L<Apache::MVC>, L<CGI::Maypole>.
556
557 =head1 AUTHOR
558
559 Maypole is currently maintained by Simon Flack C<simonflk#cpan.org>
560
561 =head1 AUTHOR EMERITUS
562
563 Simon Cozens, C<simon#cpan.org>
564
565 Sebastian Riedel, C<sri#oook.de> maintained Maypole from 1.99_01 to 2.04
566
567 =head1 THANKS TO
568
569 Sebastian Riedel, Danijel Milicevic, Dave Slack, Jesse Sheidlower, Jody Belka,
570 Marcus Ramberg, Mickael Joanne, Randal Schwartz, Simon Flack, Steve Simms,
571 Veljko Vidovic and all the others who've helped.
572
573 =head1 LICENSE
574
575 You may distribute this code under the same terms as Perl itself.
576
577 =cut
578
579 1;