2 use base qw(Class::Accessor::Fast Class::Data::Inheritable);
3 use UNIVERSAL::require;
7 use Maypole::Constants;
11 our $VERSION = '2.11';
13 # proposed privacy conventions:
14 # - no leading underscore - public to custom application code and plugins
15 # - single leading underscore - private to the main Maypole stack - *not*
17 # - double leading underscore - private to the current package
19 __PACKAGE__->mk_classdata($_) for qw( config init_done view_object );
20 __PACKAGE__->mk_accessors(
21 qw( params query objects model_class template_args output path
22 args action template error document_encoding content_type table
23 headers_in headers_out stash)
25 __PACKAGE__->config( Maypole::Config->new() );
26 __PACKAGE__->init_done(0);
32 my $calling_class = shift;
34 $calling_class = ref $calling_class if ref $calling_class;
36 my $config = $calling_class->config;
38 $config->model || $config->model('Maypole::Model::CDBI');
40 $config->model->require or die sprintf
41 "Couldn't load the model class %s: %s", $config->model, $@;
43 $config->model->setup_database($config, $calling_class, @_);
45 foreach my $subclass ( @{ $config->classes } )
48 unshift @{ $subclass . "::ISA" }, $config->model;
49 $config->model->adopt($subclass)
50 if $config->model->can("adopt");
57 my $config = $class->config;
58 $config->view || $config->view("Maypole::View::TT");
59 $config->view->require;
60 die "Couldn't load the view class " . $config->view . ": $@" if $@;
61 $config->display_tables
62 || $config->display_tables( $class->config->tables );
63 $class->view_object( $class->config->view->new );
74 config => $class->config,
80 # handler() has a method attribute so that mod_perl will invoke
81 # BeerDB->handler() as a method rather than a plain function
82 # BeerDB::handler() and so this inherited implementation will be
83 # found. See e.g. "Practical mod_perl" by Bekman & Cholet for
84 # more information <http://modperlbook.org/html/ch25_01.html>
87 # See Maypole::Workflow before trying to understand this.
88 my ($class, $req) = @_;
90 $class->init unless $class->init_done;
92 my $self = $class->new;
94 # initialise the request
95 $self->headers_out(Maypole::Headers->new);
96 $self->get_request($req);
97 $self->parse_location;
99 my $status = $self->handler_guts;
101 # moving this here causes unit test failures - need to check why
102 # before committing the move
103 #$status = $self->__call_process_view unless $self->output;
105 return $status unless $status == OK;
112 # The root of all evil
119 my $applicable = $self->is_model_applicable;
121 $self->__setup_plain_template unless $applicable;
123 # We authenticate every request, needed for proper session management
126 eval { $status = $self->call_authenticate };
128 if ( my $error = $@ )
130 $status = $self->call_exception($error);
134 warn "caught authenticate error: $error";
135 return $self->debug ?
136 $self->view_object->error($self, $error) : ERROR;
140 if ( $self->debug and $status != OK and $status != DECLINED )
142 $self->view_object->error( $self,
143 "Got unexpected status $status from calling authentication" );
146 return $status unless $status == OK;
148 # We run additional_data for every request
149 $self->additional_data;
153 eval { $self->model_class->process($self) };
155 if ( my $error = $@ )
157 $status = $self->call_exception($error);
161 warn "caught model error: $error";
162 return $self->debug ?
163 $self->view_object->error($self, $error) : ERROR;
168 # less frequent path - perhaps output has been set to an error message
169 return OK if $self->output;
171 # normal path - no output has been generated yet
172 return $self->__call_process_view;
175 # is_applicable() returned false, so set up a plain template. Model processing
176 # will be skipped, but need to remove the model anyway so the template can't
178 sub __setup_plain_template
182 # It's just a plain template
183 $self->model_class(undef);
185 my $path = $self->path;
186 $path =~ s{/$}{}; # De-absolutify
189 $self->template($self->path);
192 # The model has been processed or skipped (if is_applicable returned false),
193 # any exceptions have been handled, and there's no content in $self->output
194 sub __call_process_view
200 eval { $status = $self->view_object->process($self) };
202 if ( my $error = $@ )
204 $status = $self->call_exception($error);
208 warn "caught view error: $error" if $self->debug;
209 return $self->debug ?
210 $self->view_object->error($self, $error) : ERROR;
220 $self->model_class( $self->config->model->class_of($self, $self->table) );
223 # is_applicable() should return true or false, not OK or DECLINED, because
224 # the return value is never used as the return value from handler(). There's
225 # probably a lot of code out there supplying the return codes though, so
226 # instead of changing is_applicable() to return 0 or 1, the return value is
227 # passed through __to_boolean. I think it helps handler_guts() if we don't
228 # have multiple sets of return codes being checked for different things -drb.
229 sub is_model_applicable
233 # cater for applications that are using obsolete version
234 if ($self->can('is_applicable'))
236 warn "DEPRECATION WARNING: rewrite is_applicable to the interface ".
237 "of Maypole::is_model_applicable\n";
238 return $self->is_applicable == OK;
241 # Establish which tables should be processed by the model
242 my $config = $self->config;
244 $config->ok_tables || $config->ok_tables( $config->display_tables );
246 $config->ok_tables( { map { $_ => 1 } @{ $config->ok_tables } } )
247 if ref $config->ok_tables eq "ARRAY";
249 my $ok_tables = $config->ok_tables;
251 # Does this request concern a table to be processed by the model?
252 my $table = $self->table;
256 if (exists $ok_tables->{$table})
260 # implements tj's default_table_view(), but there's no _default_table_view()
261 # or _have_default_table_view() yet
264 # $ok = $self->default_table_view($self->path, $self->args)
265 # if $self->_have_default_table_view;
270 warn "We don't have that table ($table).\n"
271 . "Available tables are: "
272 . join( ",", keys %$ok_tables )
273 if $self->debug and not $ok_tables->{$table};
278 # Is the action public?
279 my $action = $self->action;
280 return 1 if $self->model_class->is_public($action);
282 warn "The action '$action' is not applicable to the table $table"
288 sub call_authenticate
292 # Check if we have a model class with an authenticate() to delegate to
293 return $self->model_class->authenticate($self)
294 if $self->model_class and $self->model_class->can('authenticate');
296 # Interface consistency is a Good Thing -
297 # the invocant and the argument may one day be different things
298 # (i.e. controller and request), like they are when authenticate()
299 # is called on a model class (i.e. model and request)
300 return $self->authenticate($self);
305 my ($self, $error) = @_;
307 # Check if we have a model class with an exception() to delegate to
308 if ( $self->model_class && $self->model_class->can('exception') )
310 my $status = $self->model_class->exception( $self, $error );
311 return $status if $status == OK;
314 return $self->exception($error);
317 sub default_table_view {
318 my ($self,$path,$args) = @_;
320 my $default_table_view = __PACKAGE__->_default_table_view;
321 # (path class action field)
322 my @path = $self->{path} =~ m{([^/]+)/?}g;
323 my $search_value = shift(@path);
324 if ($default_table_view->{path}) {
325 if ($default_table_view->{path} eq $search_value) {
326 $search_value = shift(@path);
332 $self->{table} = $default_table_view->{class};
333 $self->{action} = $default_table_view->{action};
334 $self->{args} = [ $search_value,@path ];
338 sub additional_data { }
340 sub authenticate { return OK }
342 sub exception { return ERROR }
348 $self->path || $self->path('frontpage');
350 my @pi = grep {length} split '/', $self->path;
352 $self->table(shift @pi);
354 $self->action( shift @pi or 'index' );
366 if (@_ == 1 and ref $_[0] and ref $_[0] eq 'HASH')
370 elsif ( @_ > 1 and @_ < 4 )
372 $args{table} = shift;
373 $args{action} = shift;
374 $args{additional} = shift;
381 do { die "no $_" unless $args{$_} } for qw( table action );
383 my $additional = $args{additional} || $args{id};
389 # if $additional is a href, make_uri() will transform it into a query
390 @add = (ref $additional eq 'ARRAY') ? @$additional : ($additional);
393 my $uri = $r->make_uri($args{table}, $args{action}, @add);
395 return $uri->as_string;
400 my ($r, @segments) = @_;
402 my $query = (ref $segments[-1] eq 'HASH') ? pop(@segments) : undef;
404 my $base = $r->config->uri_base;
407 my $uri = URI->new($base);
408 $uri->path_segments($uri->path_segments, grep {length} @segments);
410 my $abs_uri = $uri->abs('/');
411 $abs_uri->query_form($query) if $query;
416 # like CGI::param(), but read only
419 my ($self, $key) = @_;
421 return keys %{$self->params} unless defined $key;
423 return unless exists $self->params->{$key};
425 my $val = $self->params->{$key};
427 return ref $val ? @$val : ($val) if wantarray;
429 return ref $val ? $val->[0] : $val;
432 sub get_template_root {'.'}
436 die "get_protocol is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
440 die "parse_location is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
443 sub redirect_request {
444 die "parse_location is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
447 sub redirect_internal_request {
452 die "send_output is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
455 # Session and Repeat Submission Handling
458 use Maypole::Session;
459 return Maypole::Session::generate_unique_id();
464 Maypole - MVC web application framework
468 See L<Maypole::Application>.
472 This documents the Maypole request object. See the L<Maypole::Manual>, for a
473 detailed guide to using Maypole.
475 Maypole is a Perl web application framework similar to Java's struts. It is
476 essentially completely abstracted, and so doesn't know anything about
477 how to talk to the outside world.
479 To use it, you need to create a package which represents your entire
480 application. In our example above, this is the C<BeerDB> package.
482 This needs to first use L<Maypole::Application> which will make your package
483 inherit from the appropriate platform driver such as C<Apache::MVC> or
484 C<CGI::Maypole>, and then call setup. This sets up the model classes and
485 configures your application. The default model class for Maypole uses
486 L<Class::DBI> to map a database to classes, but this can be changed by altering
487 configuration. (B<Before> calling setup.)
493 Returns the L<Maypole::Config> object
497 My::App->setup($data_source, $user, $password, \%attr);
499 Initialise the maypole application and model classes. Your application should
500 call this after setting configuration via L<"config">
504 You should not call this directly, but you may wish to override this to
506 application-specific initialisation.
510 Constructs a very minimal new Maypole request object.
514 Get/set the Maypole::View object
518 sub My::App::debug {1}
520 Returns the debugging flag. Override this in your application class to
521 enable/disable debugging.
523 =head2 INSTANCE METHODS
525 =head3 parse_location
527 Turns the backend request (e.g. Apache::MVC, Maypole, CGI) into a
529 request. It does this by setting the C<path>, and invoking C<parse_path>
533 You should only need to define this method if you are writing a new
539 Returns the request path
543 Parses the request path and sets the C<args>, C<action> and C<table>
546 =head3 make_path( %args or \%args or @args )
548 This is the counterpart to C<parse_path>. It generates a path to use
549 in links, form actions etc. To implement your own path scheme, just override
550 this method and C<parse_path>.
552 %args = ( table => $table,
554 additional => $additional, # optional - generally an object ID
557 \%args = as above, but a ref
559 @args = ( $table, $action, $additional ); # $additional is optional
561 C<id> can be used as an alternative key to C<additional>.
563 C<$additional> can be a string, an arrayref, or a hashref. An arrayref is
564 expanded into extra path elements, whereas a hashref is translated into a query
567 =head3 make_uri( @segments )
569 Make a L<URI> object given table, action etc. Automatically adds
572 If the final element in C<@segments> is a hash ref, C<make_uri> will render it
577 The table part of the Maypole request path
581 The action part of the Maypole request path
585 A list of remaining parts of the request path after table and action
591 A L<Maypole::Headers> object containing HTTP headers for the request
595 A L<HTTP::Headers> object that contains HTTP headers for the output
599 Turns post data and query string paramaters into a hash of C<params>.
601 You should only need to define this method if you are writing a new
607 An accessor for request parameters. It behaves similarly to CGI::param() for
608 accessing CGI parameters.
612 Returns a hash of request parameters. The source of the parameters may vary
613 depending on the Maypole backend, but they are usually populated from request
614 query string and POST data.
616 B<Note:> Where muliple values of a parameter were supplied, the
619 will be an array reference.
621 =head3 get_template_root
623 Implementation-specific path to template root.
625 You should only need to define this method if you are writing a new
627 backend. Otherwise, see L<Maypole::Config/"template_root">
631 You should only need to define this method if you are writing a new
632 Maypole backend. It should return something that looks like an Apache
633 or CGI request object, it defaults to blank.
635 =head3 default_table_view
639 Returns a Maypole::Constant to indicate whether the request is valid.
641 B<This method is deprecated> as of version 2.11. If you have overridden it,
642 please override C<is_model_applicable> instead, and change the return type
643 from Maypole:Constants to true/false.
645 =head3 is_model_applicable
647 Returns true or false to indicate whether the request is valid.
649 The default implementation checks that C<< $r->table >> is publicly
650 accessible and that the model class is configured to handle the
655 Returns a Maypole::Constant to indicate whether the user is
659 The default implementation returns C<OK>
663 Returns the perl package name that will serve as the model for the
664 request. It corresponds to the request C<table> attribute.
666 =head3 additional_data
668 Called before the model processes the request, this method gives you a
670 to do some processing for each request, for example, manipulating
675 Get/set a list of model objects. The objects will be accessible in the
679 If the first item in C<$self-E<gt>args> can be C<retrieve()>d by the model
681 it will be removed from C<args> and the retrieved object will be added
683 C<objects> list. See L<Maypole::Model> for more information.
687 $self->template_args->{foo} = 'bar';
689 Get/set a hash of template variables.
693 A place to put custom application data. Not used by Maypole itself.
697 Get/set the template to be used by the view. By default, it returns
702 This method is called if any exceptions are raised during the
705 model/view processing. It should accept the exception as a parameter and
707 a Maypole::Constant to indicate whether the request should continue to
713 Get/set a request error
717 Get/set the response output. This is usually populated by the view
719 can skip view processing by setting the C<output>.
721 =head3 document_encoding
723 Get/set the output encoding. Default: utf-8.
727 Get/set the output content type. Default: text/html
731 Sends the output and additional headers to the user.
733 =head3 call_authenticate
735 This method first checks if the relevant model class
736 can authenticate the user, or falls back to the default
737 authenticate method of your Maypole application.
740 =head3 call_exception
742 This model is called to catch exceptions, first after authenticate, then after
743 processing the model class, and finally to check for exceptions from the view
746 This method first checks if the relevant model class
747 can handle exceptions the user, or falls back to the default
748 exception method of your Maypole application.
750 =head3 make_random_id
752 returns a unique id for this request can be used to prevent or detect repeat
757 Returns the protocol the request was made with, i.e. https
759 =head3 redirect_request
761 Sets output headers to redirect based on the arguments provided
763 Accepts either a single argument of the full url to redirect to, or a hash of named parameters :
765 $r->redirect_request('http://www.example.com/path');
769 $r->redirect_request(protocol=>'https', domain=>'www.example.com', path=>'/path/file?arguments', status=>'302', url=>'..');
771 The named parameters are protocol, domain, path, status and url
773 Only 1 named parameter is required but other than url, they can be combined as required and current values (from the request) will be used in place of any missing arguments. The url argument must be a full url including protocol and can only be combined with status.
775 =head3 redirect_internal_request
779 This method sets up the class if it's not done yet, sets some
780 defaults and leaves the dirty work to handler_guts.
784 This is the main request handling method and calls various methods to handle the request/response
785 and defines the workflow within Maypole.
787 Currently undocumented and liable to be refactored without warning.
791 There's more documentation, examples, and a information on our mailing lists
792 at the Maypole web site:
794 L<http://maypole.perl.org/>
796 L<Maypole::Application>, L<Apache::MVC>, L<CGI::Maypole>.
800 Maypole is currently maintained by Simon Flack C<simonflk#cpan.org>
802 =head1 AUTHOR EMERITUS
804 Simon Cozens, C<simon#cpan.org>
806 Sebastian Riedel, C<sri#oook.de> maintained Maypole from 1.99_01 to 2.04
810 Sebastian Riedel, Danijel Milicevic, Dave Slack, Jesse Sheidlower, Jody Belka,
811 Marcus Ramberg, Mickael Joanne, Randal Schwartz, Simon Flack, Steve Simms,
812 Veljko Vidovic and all the others who've helped.
816 You may distribute this code under the same terms as Perl itself.