Application.pm 79.8 KB
Newer Older
1 2 3 4
package CGI::Application;
use Carp;
use strict;
use Class::ISA;
5
use Scalar::Util;
6

7
$CGI::Application::VERSION = '4.61';
8 9 10 11 12 13 14 15

my %INSTALLED_CALLBACKS = (
#	hook name          package                 sub
	init      => { 'CGI::Application' => [ 'cgiapp_init'    ] },
	prerun    => { 'CGI::Application' => [ 'cgiapp_prerun'  ] },
	postrun   => { 'CGI::Application' => [ 'cgiapp_postrun' ] },
	teardown  => { 'CGI::Application' => [ 'teardown'       ] },
	load_tmpl => { },
16
	error     => { },
17 18 19 20 21 22 23 24
);

###################################
####  INSTANCE SCRIPT METHODS  ####
###################################

sub new {
	my $class = shift;
25

26 27 28 29 30 31 32 33
	my @args = @_;

	if (ref($class)) {
		# No copy constructor yet!
		$class = ref($class);
	}

	# Create our object!
34 35
	my $self = {};
	bless($self, $class);
36

37 38 39 40
	### SET UP DEFAULT VALUES ###
	#
	# We set them up here and not in the setup() because a subclass
	# which implements setup() still needs default values!
41

42 43 44
	$self->header_type('header');
	$self->mode_param('rm');
	$self->start_mode('start');
45 46 47 48

	# Process optional new() parameters
	my $rprops;
	if (ref($args[0]) eq 'HASH') {
49
		$rprops = $self->_cap_hash($args[0]);
50
	} else {
51
		$rprops = $self->_cap_hash({ @args });
52 53 54 55
	}

	# Set tmpl_path()
	if (exists($rprops->{TMPL_PATH})) {
56
		$self->tmpl_path($rprops->{TMPL_PATH});
57 58 59 60
	}

	# Set CGI query object
	if (exists($rprops->{QUERY})) {
61
		$self->query($rprops->{QUERY});
62 63 64 65 66 67 68
	}

	# Set up init param() values
	if (exists($rprops->{PARAMS})) {
		croak("PARAMS is not a hash ref") unless (ref($rprops->{PARAMS}) eq 'HASH');
		my $rparams = $rprops->{PARAMS};
		while (my ($k, $v) = each(%$rparams)) {
69
			$self->param($k, $v);
70 71 72 73
		}
	}

	# Lock prerun_mode from being changed until cgiapp_prerun()
74
	$self->{__PRERUN_MODE_LOCKED} = 1;
75 76 77 78

	# Call cgiapp_init() method, which may be implemented in the sub-class.
	# Pass all constructor args forward.  This will allow flexible usage
	# down the line.
79
	$self->call_hook('init', @args);
80 81

	# Call setup() method, which should be implemented in the sub-class!
82
	$self->setup();
83

84
	return $self;
85 86
}

87
sub __get_runmode {
88
	my $self     = shift;
89
	my $rm_param = shift;
90 91 92 93 94

	my $rm;
	# Support call-back instead of CGI mode param
	if (ref($rm_param) eq 'CODE') {
		# Get run mode from subref
95
		$rm = $rm_param->($self);
96 97 98 99 100 101 102
	}
	# support setting run mode from PATH_INFO
	elsif (ref($rm_param) eq 'HASH') {
		$rm = $rm_param->{run_mode};
	}
	# Get run mode from CGI param
	else {
103
		$rm = $self->query->param($rm_param);
104 105 106
	}

	# If $rm undefined, use default (start) mode
107
	$rm = $self->start_mode unless defined($rm) && length($rm);
108

109 110
	return $rm;
}
111

112
sub __get_runmeth {
113
	my $self = shift;
114
	my $rm   = shift;
115

116
	my $rmeth;
117

118
    my $is_autoload = 0;
119

120
	my %rmodes = ($self->run_modes());
121 122
	if (exists($rmodes{$rm})) {
		$rmeth = $rmodes{$rm};
123 124
	}
    else {
125 126 127 128 129
		# Look for run mode "AUTOLOAD" before dieing
		unless (exists($rmodes{'AUTOLOAD'})) {
			croak("No such run mode '$rm'");
		}
		$rmeth = $rmodes{'AUTOLOAD'};
130
        $is_autoload = 1;
131 132
	}

133 134 135 136
	return ($rmeth, $is_autoload);
}

sub __get_body {
137
	my $self  = shift;
138 139
	my $rm    = shift;

140
	my ($rmeth, $is_autoload) = $self->__get_runmeth($rm);
141

142 143
	my $body;
	eval {
144
        $body = $is_autoload ? $self->$rmeth($rm) : $self->$rmeth();
145 146 147
	};
	if ($@) {
		my $error = $@;
148 149 150
		$self->call_hook('error', $error);
		if (my $em = $self->error_mode) {
			$body = $self->$em( $error );
151
		} else {
152
			croak("Error executing run mode '$rm': $error");
153 154 155
		}
	}

156 157 158 159 160 161 162
	# Make sure that $body is not undefined (suppress 'uninitialized value'
	# warnings)
	return defined $body ? $body : '';
}


sub run {
163 164
	my $self = shift;
	my $q = $self->query();
165

166
	my $rm_param = $self->mode_param();
167

168
	my $rm = $self->__get_runmode($rm_param);
169 170

	# Set get_current_runmode() for access by user later
171
	$self->{__CURRENT_RUNMODE} = $rm;
172 173

	# Allow prerun_mode to be changed
174
	delete($self->{__PRERUN_MODE_LOCKED});
175 176 177 178

	# Call PRE-RUN hook, now that we know the run mode
	# This hook can be used to provide run mode specific behaviors
	# before the run mode actually runs.
179
 	$self->call_hook('prerun', $rm);
180 181

	# Lock prerun_mode from being changed after cgiapp_prerun()
182
	$self->{__PRERUN_MODE_LOCKED} = 1;
183 184

	# If prerun_mode has been set, use it!
185
	my $prerun_mode = $self->prerun_mode();
186 187
	if (length($prerun_mode)) {
		$rm = $prerun_mode;
188
		$self->{__CURRENT_RUNMODE} = $rm;
189 190 191
	}

	# Process run mode!
192
	my $body = $self->__get_body($rm);
193 194

	# Support scalar-ref for body return
195
	$body = $$body if ref $body eq 'SCALAR';
196 197

	# Call cgiapp_postrun() hook
198
	$self->call_hook('postrun', \$body);
199

200 201 202
	my $return_value;
	if ($self->{__IS_PSGI}) {
		my ($status, $headers) = $self->_send_psgi_headers();
203

204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
		if (ref($body) eq 'GLOB' || (Scalar::Util::blessed($body) && $body->can('getline'))) {
			# body a file handle - return it
			$return_value = [ $status, $headers, $body];
		}
		elsif (ref($body) eq 'CODE') {

			# body is a subref, or an explicit callback method is set
			$return_value = sub {
				my $respond = shift;

				my $writer = $respond->([ $status, $headers ]);

				&$body($writer);
			};
		}
		else {

			$return_value = [ $status, $headers, [ $body ]];
		}
	}
	else {
		# Set up HTTP headers non-PSGI responses
		my $headers = $self->_send_headers();

		# Build up total output
		$return_value  = $headers.$body;
		print $return_value unless $ENV{CGI_APP_RETURN_ONLY};
	}
232 233

	# clean up operations
234
	$self->call_hook('teardown');
235

236 237 238 239 240 241 242 243 244 245
	return $return_value;
}


sub psgi_app {
    my $class = shift;
    my $args_to_new = shift;

    return sub {
        my $env = shift;
246 247 248
	
	# PR from alter https://github.com/markstos/CGI--Application/pull/17
        #if (not defined $args_to_new->{QUERY}) {
249 250
            require CGI::PSGI;
            $args_to_new->{QUERY} = CGI::PSGI->new($env);
251
        #}
252 253 254 255 256 257 258 259 260 261 262 263

        my $webapp = $class->new($args_to_new);
        return $webapp->run_as_psgi;
    }
}

sub run_as_psgi {
    my $self = shift;
    $self->{__IS_PSGI} = 1;

    # Run doesn't officially support any args, but pass them through in case some sub-class uses them.
    return $self->run(@_);
264 265 266 267 268 269 270 271
}


############################
####  OVERRIDE METHODS  ####
############################

sub cgiapp_get_query {
272
	my $self = shift;
273 274 275 276 277 278 279 280 281 282 283 284

	# Include CGI.pm and related modules
	require CGI;

	# Get the query object
	my $q = CGI->new();

	return $q;
}


sub cgiapp_init {
285
	my $self = shift;
286 287 288 289 290 291 292
	my @args = (@_);

	# Nothing to init, yet!
}


sub cgiapp_prerun {
293
	my $self = shift;
294 295 296 297 298 299 300
	my $rm = shift;

	# Nothing to prerun, yet!
}


sub cgiapp_postrun {
301
	my $self = shift;
302 303 304 305 306 307 308
	my $bodyref = shift;

	# Nothing to postrun, yet!
}


sub setup {
309
	my $self = shift;
310 311 312 313
}


sub teardown {
314
	my $self = shift;
315 316 317 318 319 320 321 322 323 324 325 326

	# Nothing to shut down, yet!
}




######################################
####  APPLICATION MODULE METHODS  ####
######################################

sub dump {
327
	my $self = shift;
328 329 330
	my $output = '';

	# Dump run mode
331
	my $current_runmode = $self->get_current_runmode();
332 333 334 335
	$current_runmode = "" unless (defined($current_runmode));
	$output .= "Current Run mode: '$current_runmode'\n";

	# Dump Params
336
	# updated ->param to ->multi_param to silence CGI.pm warning
337
	$output .= "\nQuery Parameters:\n";
338
	my @params = $self->query->multi_param();
339
	foreach my $p (sort(@params)) {
340
		my @data = $self->query->multi_param($p);
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
		my $data_str = "'".join("', '", @data)."'";
		$output .= "\t$p => $data_str\n";
	}

	# Dump ENV
	$output .= "\nQuery Environment:\n";
	foreach my $ek (sort(keys(%ENV))) {
		$output .= "\t$ek => '".$ENV{$ek}."'\n";
	}

	return $output;
}


sub dump_html {
356 357
	my $self   = shift;
	my $query  = $self->query();
358 359 360
	my $output = '';

	# Dump run-mode
361
	my $current_runmode = $self->get_current_runmode();
362
	$output .= "<p>Current Run-mode:
363
	'<strong>$current_runmode</strong>'</p>\n";
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

	# Dump Params
	$output .= "<p>Query Parameters:</p>\n";
	$output .= $query->Dump;

	# Dump ENV
	$output .= "<p>Query Environment:</p>\n<ol>\n";
	foreach my $ek ( sort( keys( %ENV ) ) ) {
		$output .= sprintf(
			"<li> %s => '<strong>%s</strong>'</li>\n",
			$query->escapeHTML( $ek ),
			$query->escapeHTML( $ENV{$ek} )
		);
	}
	$output .= "</ol>\n";

	return $output;
}


384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
sub no_runmodes {

	my $self   = shift;
	my $query  = $self->query();
	my $output = $query->start_html;
	
	# If no runmodes specified by app return error message 
	my $current_runmode = $self->get_current_runmode();
	my $query_params = $query->Dump;
	
	$output .= qq{
		<h2>Error - No runmodes specified.</h2>
		<p>Runmode called: $current_runmode"</p>
		<p>Query paramaters:</p> $query_params
		<p>Your application has not specified any runmodes.</p>
		<p>Please read the <a href="https://metacpan.org/pod/CGI::Application">
		CGI::Application</a> documentation.</p>
	};
	
	$output .= $query->end_html();
	return $output;
}


408
sub header_add {
409 410
	my $self = shift;
	return $self->_header_props_update(\@_,add=>1);
411 412 413
}

sub header_props {
414 415
	my $self = shift;
	return $self->_header_props_update(\@_,add=>0);
416 417 418 419
}

# used by header_props and header_add to update the headers
sub _header_props_update {
420
	my $self     = shift;
421 422 423 424 425 426
	my $data_ref = shift;
	my %in       = @_;

	my @data = @$data_ref;

	# First use?  Create new __HEADER_PROPS!
427
	$self->{__HEADER_PROPS} = {} unless (exists($self->{__HEADER_PROPS}));
428 429 430 431 432

	my $props;

	# If data is provided, set it!
	if (scalar(@data)) {
433
        if ($self->header_type eq 'none') {
434
		    warn "header_props called while header_type set to 'none', headers will NOT be sent!"
435
        }
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
		# Is it a hash, or hash-ref?
		if (ref($data[0]) eq 'HASH') {
			# Make a copy
			%$props = %{$data[0]};
		} elsif ((scalar(@data) % 2) == 0) {
			# It appears to be a possible hash (even # of elements)
			%$props = @data;
		} else {
			my $meth = $in{add} ? 'add' : 'props';
			croak("Odd number of elements passed to header_$meth().  Not a valid hash")
		}

		# merge in new headers, appending new values passed as array refs
		if ($in{add}) {
			for my $key_set_to_aref (grep { ref $props->{$_} eq 'ARRAY'} keys %$props) {
451
				my $existing_val = $self->{__HEADER_PROPS}->{$key_set_to_aref};
452 453 454 455
				next unless defined $existing_val;
				my @existing_val_array = (ref $existing_val eq 'ARRAY') ? @$existing_val : ($existing_val);
				$props->{$key_set_to_aref} = [ @existing_val_array, @{ $props->{$key_set_to_aref} } ];
			}
456
			$self->{__HEADER_PROPS} = { %{ $self->{__HEADER_PROPS} }, %$props };
457 458 459
		}
		# Set new headers, clobbering existing values
		else {
460
			$self->{__HEADER_PROPS} = $props;
461 462 463 464 465
		}

	}

	# If we've gotten this far, return the value!
466
	return (%{ $self->{__HEADER_PROPS}});
467 468 469 470
}


sub header_type {
471
	my $self = shift;
472 473 474 475 476
	my ($header_type) = @_;

	my @allowed_header_types = qw(header redirect none);

	# First use?  Create new __HEADER_TYPE!
477
	$self->{__HEADER_TYPE} = 'header' unless (exists($self->{__HEADER_TYPE}));
478 479 480 481 482 483

	# If data is provided, set it!
	if (defined($header_type)) {
		$header_type = lc($header_type);
		croak("Invalid header_type '$header_type'")
			unless(grep { $_ eq $header_type } @allowed_header_types);
484
		$self->{__HEADER_TYPE} = $header_type;
485 486 487
	}

	# If we've gotten this far, return the value!
488
	return $self->{__HEADER_TYPE};
489 490 491 492
}


sub param {
493
	my $self = shift;
494 495 496
	my (@data) = (@_);

	# First use?  Create new __PARAMS!
497
	$self->{__PARAMS} = {} unless (exists($self->{__PARAMS}));
498

499
	my $rp = $self->{__PARAMS};
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

	# If data is provided, set it!
	if (scalar(@data)) {
		# Is it a hash, or hash-ref?
		if (ref($data[0]) eq 'HASH') {
			# Make a copy, which augments the existing contents (if any)
			%$rp = (%$rp, %{$data[0]});
		} elsif ((scalar(@data) % 2) == 0) {
			# It appears to be a possible hash (even # of elements)
			%$rp = (%$rp, @data);
		} elsif (scalar(@data) > 1) {
			croak("Odd number of elements passed to param().  Not a valid hash");
		}
	} else {
		# Return the list of param keys if no param is specified.
		return (keys(%$rp));
	}

	# If exactly one parameter was sent to param(), return the value
	if (scalar(@data) <= 2) {
		my $param = $data[0];
		return $rp->{$param};
	}
	return;  # Otherwise, return undef
}


sub delete {
528
	my $self = shift;
529 530
	my ($param) = @_;

531 532 533
	# return undef it the param name isn't given
	return undef unless defined $param;

534 535
	#simply delete this param from $self->{__PARAMS}
	delete $self->{__PARAMS}->{$param};
536 537 538 539
}


sub query {
540
	my $self = shift;
541 542
	my ($query) = @_;

543 544 545 546 547 548 549
	# If data is provided, set it!  Otherwise, create a new one.
	if (defined($query)) {
		$self->{__QUERY_OBJ} = $query;
	} else {
		# We're only allowed to create a new query object if one does not yet exist!
		unless (exists($self->{__QUERY_OBJ})) {
			$self->{__QUERY_OBJ} = $self->cgiapp_get_query();
550 551 552
		}
	}

553
	return $self->{__QUERY_OBJ};
554 555 556 557
}


sub run_modes {
558
	my $self = shift;
559 560 561
	my (@data) = (@_);

	# First use?  Create new __RUN_MODES!
562
	$self->{__RUN_MODES} = { 'start' => 'no_runmodes' } unless (exists($self->{__RUN_MODES}));
563

564
	my $rr_m = $self->{__RUN_MODES};
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

	# If data is provided, set it!
	if (scalar(@data)) {
		# Is it a hash, hash-ref, or array-ref?
		if (ref($data[0]) eq 'HASH') {
			# Make a copy, which augments the existing contents (if any)
			%$rr_m = (%$rr_m, %{$data[0]});
		} elsif (ref($data[0]) eq 'ARRAY') {
			# Convert array-ref into hash table
			foreach my $rm (@{$data[0]}) {
				$rr_m->{$rm} = $rm;
			}
		} elsif ((scalar(@data) % 2) == 0) {
			# It appears to be a possible hash (even # of elements)
			%$rr_m = (%$rr_m, @data);
		} else {
			croak("Odd number of elements passed to run_modes().  Not a valid hash");
		}
	}

	# If we've gotten this far, return the value!
	return (%$rr_m);
}


sub start_mode {
591
	my $self = shift;
592 593 594
	my ($start_mode) = @_;

	# First use?  Create new __START_MODE
595
	$self->{__START_MODE} = 'start' unless (exists($self->{__START_MODE}));
596 597 598

	# If data is provided, set it
	if (defined($start_mode)) {
599
		$self->{__START_MODE} = $start_mode;
600 601
	}

602
	return $self->{__START_MODE};
603 604 605 606
}


sub error_mode {
607
	my $self = shift;
608 609 610
	my ($error_mode) = @_;

	# First use?  Create new __ERROR_MODE
611
	$self->{__ERROR_MODE} = undef unless (exists($self->{__ERROR_MODE}));
612 613 614

	# If data is provided, set it.
	if (defined($error_mode)) {
615
		$self->{__ERROR_MODE} = $error_mode;
616 617
	}

618
	return $self->{__ERROR_MODE};
619 620 621 622
}


sub tmpl_path {
623
	my $self = shift;
624 625 626
	my ($tmpl_path) = @_;

	# First use?  Create new __TMPL_PATH!
627
	$self->{__TMPL_PATH} = '' unless (exists($self->{__TMPL_PATH}));
628 629 630

	# If data is provided, set it!
	if (defined($tmpl_path)) {
631
		$self->{__TMPL_PATH} = $tmpl_path;
632 633 634
	}

	# If we've gotten this far, return the value!
635
	return $self->{__TMPL_PATH};
636 637 638 639
}


sub prerun_mode {
640
	my $self = shift;
641 642 643
	my ($prerun_mode) = @_;

	# First use?  Create new __PRERUN_MODE
644
	$self->{__PRERUN_MODE} = '' unless (exists($self->{__PRERUN_MODE}));
645 646 647 648

	# Was data provided?
	if (defined($prerun_mode)) {
		# Are we allowed to set prerun_mode?
649
		if (exists($self->{__PRERUN_MODE_LOCKED})) {
650 651 652 653
			# Not allowed!  Throw an exception.
			croak("prerun_mode() can only be called within cgiapp_prerun()!  Error");
		} else {
			# If data is provided, set it!
654
			$self->{__PRERUN_MODE} = $prerun_mode;
655 656 657 658
		}
	}

	# If we've gotten this far, return the value!
659
	return $self->{__PRERUN_MODE};
660 661 662 663
}


sub get_current_runmode {
664
	my $self = shift;
665 666

	# It's OK if we return undef if this method is called too early
667
	return $self->{__CURRENT_RUNMODE};
668 669 670 671 672 673 674 675 676 677 678
}





###########################
####  PRIVATE METHODS  ####
###########################


679
# return headers as a string
680
sub _send_headers {
681 682 683
	my $self = shift;
	my $q    = $self->query;
	my $type = $self->header_type;
684 685

    return
686 687
        $type eq 'redirect' ? $q->redirect( $self->header_props )
      : $type eq 'header'   ? $q->header  ( $self->header_props )
688 689
      : $type eq 'none'     ? ''
      : croak "Invalid header_type '$type'"
690 691
}

692 693 694 695 696 697 698 699 700 701 702 703 704 705
# return a 2 element array modeling the first PSGI redirect values: status code and arrayref of header pairs
sub _send_psgi_headers {
	my $self = shift;
	my $q    = $self->query;
	my $type = $self->header_type;

    return
        $type eq 'redirect' ? $q->psgi_redirect( $self->header_props )
      : $type eq 'header'   ? $q->psgi_header  ( $self->header_props )
      : $type eq 'none'     ? ''
      : croak "Invalid header_type '$type'"

}

706 707

# Make all hash keys CAPITAL
708 709
# although this method is internal, some other extensions
# have come to rely on it, so any changes here should be
710
# made with great care or avoided.
711
sub _cap_hash {
712
	my $self = shift;
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
	my $rhash = shift;
	my %hash = map {
		my $k = $_;
		my $v = $rhash->{$k};
		$k =~ tr/a-z/A-Z/;
		$k => $v;
	} keys(%{$rhash});
	return \%hash;
}



1;




=pod

=head1 NAME

734
CGI::Application - Framework for building reusable web-applications
735 736 737 738 739 740

=head1 SYNOPSIS

  # In "WebApp.pm"...
  package WebApp;
  use base 'CGI::Application';
741 742

  # ( setup() can even be skipped for common cases. See docs below. )
743
  sub setup {
744 745 746 747
	my $self = shift;
	$self->start_mode('mode1');
	$self->mode_param('rm');
	$self->run_modes(
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
		'mode1' => 'do_stuff',
		'mode2' => 'do_more_stuff',
		'mode3' => 'do_something_else'
	);
  }
  sub do_stuff { ... }
  sub do_more_stuff { ... }
  sub do_something_else { ... }
  1;


  ### In "webapp.cgi"...
  use WebApp;
  my $webapp = WebApp->new();
  $webapp->run();

764 765 766 767
  ### Or, in a PSGI file, webapp.psgi
  use WebApp;
  WebApp->psgi_app();

768
=head1 INTRODUCTION
769

770 771 772
CGI::Application makes it easier to create sophisticated, high-performance,
reusable web-based applications.  CGI::Application helps makes your web
applications easier to design, write, and evolve.
773

774 775
CGI::Application judiciously avoids employing technologies and techniques which
would bind a developer to any one set of tools, operating system or web server.
776

777
It is lightweight in terms of memory usage, making it suitable for common CGI
778 779 780 781
environments, and a high performance choice in persistent environments like
FastCGI or mod_perl.

By adding L<PLUG-INS> as your needs grow, you can add advanced and complex
782
features when you need them.
783 784

First released in 2000 and used and expanded by a number of professional
785
website developers, CGI::Application is a stable, reliable choice.
786

787
=head1 USAGE EXAMPLE
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823

Imagine you have to write an application to search through a database
of widgets.  Your application has three screens:

   1. Search form
   2. List of results
   3. Detail of a single record

To write this application using CGI::Application you will create two files:

   1. WidgetView.pm -- Your "Application Module"
   2. widgetview.cgi -- Your "Instance Script"

The Application Module contains all the code specific to your
application functionality, and it exists outside of your web server's
document root, somewhere in the Perl library search path.

The Instance Script is what is actually called by your web server.  It is
a very small, simple file which simply creates an instance of your
application and calls an inherited method, run().  Following is the
entirety of "widgetview.cgi":

   #!/usr/bin/perl -w
   use WidgetView;
   my $webapp = WidgetView->new();
   $webapp->run();

As you can see, widgetview.cgi simply "uses" your Application module
(which implements a Perl package called "WidgetView").  Your Application Module,
"WidgetView.pm", is somewhat more lengthy:

   package WidgetView;
   use base 'CGI::Application';
   use strict;

   # Needed for our database connection
824
   use CGI::Application::Plugin::DBH;
825 826

   sub setup {
827 828 829
	my $self = shift;
	$self->start_mode('mode1');
	$self->run_modes(
830 831 832 833 834
		'mode1' => 'showform',
		'mode2' => 'showlist',
		'mode3' => 'showdetail'
	);

835
	# Connect to DBI database, with the same args as DBI->connect();
836
     $self->dbh_config();
837 838 839
   }

   sub teardown {
840
	my $self = shift;
841

842
	# Disconnect when we're done, (Although DBI usually does this automatically)
843
	$self->dbh->disconnect();
844 845 846
   }

   sub showform {
847
	my $self = shift;
848 849

	# Get CGI query object
850
	my $q = $self->query();
851 852 853 854 855 856 857 858 859 860 861 862 863 864

	my $output = '';
	$output .= $q->start_html(-title => 'Widget Search Form');
	$output .= $q->start_form();
	$output .= $q->textfield(-name => 'widgetcode');
	$output .= $q->hidden(-name => 'rm', -value => 'mode2');
	$output .= $q->submit();
	$output .= $q->end_form();
	$output .= $q->end_html();

	return $output;
   }

   sub showlist {
865
	my $self = shift;
866 867

	# Get our database connection
868
	my $dbh = $self->dbh();
869 870

	# Get CGI query object
871
	my $q = $self->query();
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
	my $widgetcode = $q->param("widgetcode");

	my $output = '';
	$output .= $q->start_html(-title => 'List of Matching Widgets');

	## Do a bunch of stuff to select "widgets" from a DBI-connected
	## database which match the user-supplied value of "widgetcode"
	## which has been supplied from the previous HTML form via a
	## CGI.pm query object.
	##
	## Each row will contain a link to a "Widget Detail" which
	## provides an anchor tag, as follows:
	##
	##   "widgetview.cgi?rm=mode3&widgetid=XXX"
	##
	##  ...Where "XXX" is a unique value referencing the ID of
	## the particular "widget" upon which the user has clicked.

	$output .= $q->end_html();

	return $output;
   }

   sub showdetail {
896
	my $self = shift;
897 898

	# Get our database connection
899
	my $dbh = $self->dbh();
900 901

	# Get CGI query object
902
	my $q = $self->query();
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
	my $widgetid = $q->param("widgetid");

	my $output = '';
	$output .= $q->start_html(-title => 'Widget Detail');

	## Do a bunch of things to select all the properties of
	## the particular "widget" upon which the user has
	## clicked.  The key id value of this widget is provided
	## via the "widgetid" property, accessed via the CGI.pm
	## query object.

	$output .= $q->end_html();

	return $output;
   }

   1;  # Perl requires this at the end of all modules


CGI::Application takes care of implementing the new() and the run()
methods.  Notice that at no point do you call print() to send any
output to STDOUT.  Instead, all output is returned as a scalar.

CGI::Application's most significant contribution is in managing
the application state.  Notice that all which is needed to push
the application forward is to set the value of a HTML form
parameter 'rm' to the value of the "run mode" you wish to handle
the form submission.  This is the key to CGI::Application.


=head1 ABSTRACT

The guiding philosophy behind CGI::Application is that a web-based
application can be organized into a specific set of "Run Modes."
Each Run Mode is roughly analogous to a single screen (a form, some
output, etc.).  All the Run Modes are managed by a single "Application
Module" which is a Perl module.  In your web server's document space
there is an "Instance Script" which is called by the web server as a
CGI (or an Apache::Registry script if you're using Apache + mod_perl).

This methodology is an inversion of the "Embedded" philosophy (ASP, JSP,
EmbPerl, Mason, etc.) in which there are "pages" for each state of the
application, and the page drives functionality.  In CGI::Application,
form follows function -- the Application Module drives pages, and the
code for a single application is in one place; not spread out over
multiple "pages".  If you feel that Embedded architectures are
confusing, unorganized, difficult to design and difficult to manage,
CGI::Application is the methodology for you!

Apache is NOT a requirement for CGI::Application.  Web applications based on
CGI::Application will run equally well on NT/IIS or any other
954
CGI-compatible environment.  CGI::Application-based projects
955
are, however, ripe for use on Apache/mod_perl servers, as they
956
naturally encourage Good Programming Practices and will often work
957
in persistent environments without modification.
958

959 960
For more information on using CGI::Application with mod_perl, please see our
website at http://www.cgi-app.org/, as well as
961
L<CGI::Application::Plugin::Apache>, which integrates with L<Apache::Request>.
962 963 964

=head1 DESCRIPTION

965 966
It is intended that your Application Module will be implemented as a sub-class
of CGI::Application. This is done simply as follows:
967

968
    package My::App;
969 970 971 972 973 974 975 976 977 978 979
    use base 'CGI::Application';

B<Notation and Conventions>

For the purpose of this document, we will refer to the
following conventions:

  WebApp.pm   The Perl module which implements your Application Module class.
  WebApp      Your Application Module class; a sub-class of CGI::Application.
  webapp.cgi  The Instance Script which implements your Application Module.
  $webapp     An instance (object) of your Application Module class.
980 981
  $c          Same as $webapp, used in instance methods to pass around the
              current object. (Sometimes referred as "$self" in other code)
982 983 984 985 986 987 988 989 990 991




=head2 Instance Script Methods

By inheriting from CGI::Application you have access to a
number of built-in methods.  The following are those which
are expected to be called from your Instance Script.

992
=head3 new()
993 994 995 996 997

The new() method is the constructor for a CGI::Application.  It returns
a blessed reference to your Application Module package (class).  Optionally,
new() may take a set of parameters as key => value pairs:

998
    my $webapp = WebApp->new(
999 1000 1001 1002 1003 1004 1005 1006 1007
		TMPL_PATH => 'App/',
		PARAMS => {
			'custom_thing_1' => 'some val',
			'another_custom_thing' => [qw/123 456/]
		}
    );

This method may take some specific parameters:

1008 1009 1010 1011 1012 1013
B<TMPL_PATH> - This optional parameter defines a path to a directory of templates.
This is used by the load_tmpl() method (specified below), and may also be used
for the same purpose by other template plugins.  This run-time parameter allows
you to further encapsulate instantiating templates, providing potential for
more re-usability.  It can be either a scalar or an array reference of multiple
paths.
1014

1015 1016 1017 1018 1019 1020 1021
B<QUERY> - This optional parameter allows you to specify an
already-created CGI.pm query object.  Under normal use,
CGI::Application will instantiate its own CGI.pm query object.
Under certain conditions, it might be useful to be able to use
one which has already been created.

B<PARAMS> - This parameter, if used, allows you to set a number
1022 1023 1024 1025 1026 1027 1028 1029 1030
of custom parameters at run-time.  By passing in different
values in different instance scripts which use the same application
module you can achieve a higher level of re-usability.  For instance,
imagine an application module, "Mailform.pm".  The application takes
the contents of a HTML form and emails it to a specified recipient.
You could have multiple instance scripts throughout your site which
all use this "Mailform.pm" module, but which set different recipients
or different forms.

1031 1032 1033 1034 1035
One common use of instance scripts is to provide a path to a config file.  This
design allows you to define project wide configuration objects used by many
several instance scripts. There are several plugins which simplify the syntax
for this and provide lazy loading. Here's an example using
L<CGI::Application::Plugin::ConfigAuto>, which uses L<Config::Auto> to support
1036
many configuration file formats.
1037 1038 1039 1040

 my $app = WebApp->new(PARAMS => { cfg_file => 'config.pl' });

 # Later in your app:
1041 1042
 my %cfg = $self->cfg()
 # or ... $self->cfg('HTML_ROOT_DIR');
1043

1044
See the list of plugins below for more config file integration solutions.
1045

1046
=head3 run()
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

The run() method is called upon your Application Module object, from
your Instance Script.  When called, it executes the functionality
in your Application Module.

    my $webapp = WebApp->new();
    $webapp->run();

This method first determines the application state by looking at the
value of the CGI parameter specified by mode_param() (defaults to
'rm' for "Run Mode"), which is expected to contain the name of the mode of
operation.  If not specified, the state defaults to the value
of start_mode().

Once the mode has been determined, run() looks at the dispatch
table stored in run_modes() and finds the function pointer which
is keyed from the mode name.  If found, the function is called and the
data returned is print()'ed to STDOUT and to the browser.  If
the specified mode is not found in the run_modes() table, run() will
croak().

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
=head2 PSGI support

CGI::Application offers native L<PSGI> support. The default query object
for this is L<CGI::PSGI>, which simply wrappers CGI.pm to provide PSGI
support to it.

=head3 psgi_app()

 $psgi_coderef = WebApp->psgi_app({ ... args to new() ... });

The simplest way to create and return a PSGI-compatible coderef. Pass in
arguments to a hashref just as would to new. This returns a PSGI-compatible
coderef, using L<CGI:::PSGI> as the query object. To use a different query
object, construct your own object using C<< run_as_psgi() >>, as shown below.

It's possible that we'll change from CGI::PSGI to a different-but-compatible
query object for PSGI support in the future, perhaps if CGI.pm adds native
PSGI support.

=head3 run_as_psgi()

 my $psgi_aref = $webapp->run_as_psgi;

Just like C<< run >>, but prints no output and returns the data structure
required by the L<PSGI> specification. Use this if you want to run the
application on top of a PSGI-compatible handler, such as L<Plack> provides.

If you are just getting started, just use C<< run() >>. It's easy to switch to using
C<< run_as_psgi >> later.

Why use C<< run_as_psgi() >>? There are already solutions to run
CGI::Application-based projects on several web servers with dozens of plugins.
Running as a PSGI-compatible application provides the ability to run on
additional PSGI-compatible servers, as well as providing access to all of the
"Middleware" solutions available through the L<Plack> project.

The structure returned is an arrayref, containing the status code, an arrayref
of header key/values and an arrayref containing the body.

 [ 200, [ 'Content-Type' => 'text/html' ], [ $body ] ]

By default the body is a single scalar, but plugins may modify this to return
other value PSGI values.  See L<PSGI/"The Response"> for details about the
response format.

Note that calling C<< run_as_psgi >> only handles the I<output> portion of the
PSGI spec. to handle the input, you need to use a CGI.pm-like query object that
is PSGI-compliant, such as L<CGI::PSGI>. This query object must provide L<psgi_header>
and L<psgi_redirect> methods.

The final result might look like this:

    use WebApp;
    use CGI::PSGI;

    my $handler = sub {
        my $env = shift;
        my $webapp = WebApp->new({ QUERY => CGI::PSGI->new($env) });
        $webapp->run_as_psgi;
    };

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
=head2 Additional PSGI Return Values

The PSGI Specification allows for returning a file handle or a subroutine reference instead of byte strings.  In PSGI mode this is supported directly by CGI::Application.  Have your run mode return a file handle or compatible subref as follows:

	sub returning_a_file_handle {
	    my $self = shift;

	    $self->header_props(-type => 'text/plain');

        open my $fh, "<", 'test_file.txt' or die "OOPS! $!";

	    return $fh;
	}

    sub returning_a_subref {
        my $self = shift;

        $self->header_props(-type => 'text/plain');
        return sub {
           my $writer = shift;
           foreach my $i (1..10) {
               #sleep 1;
               $writer->write("check $i: " . time . "\n");
    		}
    	};
    }
1155 1156

=head2 Methods to possibly override
1157 1158 1159 1160

CGI::Application implements some methods which are expected to be overridden
by implementing them in your sub-class module.  These methods are as follows:

1161
=head3 setup()
1162 1163 1164 1165 1166 1167 1168 1169

This method is called by the inherited new() constructor method.  The
setup() method should be used to define the following property/methods:

    mode_param() - set the name of the run mode CGI param.
    start_mode() - text scalar containing the default run mode.
    error_mode() - text scalar containing the error mode.
    run_modes() - hash table containing mode => function mappings.
1170
    tmpl_path() - text scalar or array reference containing path(s) to template files.
1171 1172 1173 1174 1175 1176 1177 1178

Your setup() method may call any of the instance methods of your application.
This function is a good place to define properties specific to your application
via the $webapp->param() method.

Your setup() method might be implemented something like this:

	sub setup {
1179 1180 1181 1182 1183
		my $self = shift;
		$self->tmpl_path('/path/to/my/templates/');
		$self->start_mode('putform');
		$self->error_mode('my_error_rm');
		$self->run_modes({
1184 1185 1186
			'putform'  => 'my_putform_func',
			'postdata' => 'my_data_func'
		});
1187 1188 1189
		$self->param('myprop1');
		$self->param('myprop2', 'prop2value');
		$self->param('myprop3', ['p3v1', 'p3v2', 'p3v3']);
1190 1191
	}

1192
However, often times all that needs to be in setup() is defining your run modes
1193
and your start mode. L<CGI::Application::Plugin::AutoRunmode> allows you to do
1194 1195 1196 1197 1198 1199 1200
this with a simple syntax, using run mode attributes:

 use CGI::Application::Plugin::AutoRunmode;

 sub show_first : StartRunmode { ... };
 sub do_next : Runmode { ... }

1201
=head3 teardown()
1202 1203 1204 1205 1206 1207 1208 1209

If implemented, this method is called automatically after your application runs.  It
can be used to clean up after your operations.  A typical use of the
teardown() function is to disconnect a database connection which was
established in the setup() function.  You could also use the teardown()
method to store state information about the application to the server.


1210
=head3 cgiapp_init()
1211 1212 1213 1214 1215 1216 1217 1218

If implemented, this method is called automatically right before the
setup() method is called.  This method provides an optional initialization
hook, which improves the object-oriented characteristics of
CGI::Application.  The cgiapp_init() method receives, as its parameters,
all the arguments which were sent to the new() method.

An example of the benefits provided by utilizing this hook is
1219
creating a custom "application super-class" from which all
1220
your web applications would inherit, instead of CGI::Application.
1221 1222 1223 1224 1225 1226 1227

Consider the following:

  # In MySuperclass.pm:
  package MySuperclass;
  use base 'CGI::Application';
  sub cgiapp_init {
1228
	my $self = shift;
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
	# Perform some project-specific init behavior
	# such as to load settings from a database or file.
  }


  # In MyApplication.pm:
  package MyApplication;
  use base 'MySuperclass';
  sub setup { ... }
  sub teardown { ... }
  # The rest of your CGI::Application-based follows...


By using CGI::Application and the cgiapp_init() method as illustrated,
a suite of applications could be designed to share certain
characteristics.  This has the potential for much cleaner code
built on object-oriented inheritance.


1248
=head3 cgiapp_prerun()
1249 1250 1251 1252 1253 1254 1255 1256 1257

If implemented, this method is called automatically right before the
selected run mode method is called.  This method provides an optional
pre-runmode hook, which permits functionality to be added at the point
right before the run mode method is called.  To further leverage this
hook, the value of the run mode is passed into cgiapp_prerun().

Another benefit provided by utilizing this hook is
creating a custom "application super-class" from which all
1258
your web applications would inherit, instead of CGI::Application.
1259 1260 1261 1262 1263 1264 1265

Consider the following:

  # In MySuperclass.pm:
  package MySuperclass;
  use base 'CGI::Application';
  sub cgiapp_prerun {
1266
	my $self = shift;
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
	# Perform some project-specific init behavior
	# such as to implement run mode specific
	# authorization functions.
  }


  # In MyApplication.pm:
  package MyApplication;
  use base 'MySuperclass';
  sub setup { ... }
  sub teardown { ... }
  # The rest of your CGI::Application-based follows...


By using CGI::Application and the cgiapp_prerun() method as illustrated,
a suite of applications could be designed to share certain
characteristics.  This has the potential for much cleaner code
built on object-oriented inheritance.

It is also possible, within your cgiapp_prerun() method, to change the
run mode of your application.  This can be done via the prerun_mode()
method, which is discussed elsewhere in this POD.

1290
=head3 cgiapp_postrun()
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316

If implemented, this hook will be called after the run mode method
has returned its output, but before HTTP headers are generated.  This
will give you an opportunity to modify the body and headers before they
are returned to the web browser.

A typical use for this hook is pipelining the output of a CGI-Application
through a series of "filter" processors.  For example:

  * You want to enclose the output of all your CGI-Applications in
    an HTML table in a larger page.

  * Your run modes return structured data (such as XML), which you
    want to transform using a standard mechanism (such as XSLT).

  * You want to post-process CGI-App output through another system,
    such as HTML::Mason.

  * You want to modify HTTP headers in a particular way across all
    run modes, based on particular criteria.

The cgiapp_postrun() hook receives a reference to the output from
your run mode method, in addition to the CGI-App object.  A typical
cgiapp_postrun() method might be implemented as follows:

  sub cgiapp_postrun {
1317
    my $self = shift;
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    my $output_ref = shift;

    # Enclose output HTML table
    my $new_output = "<table border=1>";
    $new_output .= "<tr><td> Hello, World! </td></tr>";
    $new_output .= "<tr><td>". $$output_ref ."</td></tr>";
    $new_output .= "</table>";

    # Replace old output with new output
    $$output_ref = $new_output;
  }


Obviously, with access to the CGI-App object you have full access to use all
the methods normally available in a run mode.  You could, for example, use
1333 1334
C<load_tmpl()> to replace the static HTML in this example with HTML::Template.
You could change the HTTP headers (via C<header_type()> and C<header_props()>
1335 1336
methods) to set up a redirect.  You could also use the objects properties
to apply changes only under certain circumstance, such as a in only certain run
1337
modes, and when a C<param()> is a particular value.
1338 1339


1340
=head3 cgiapp_get_query()
1341

1342
 my $q = $webapp->cgiapp_get_query;
1343

1344
Override this method to retrieve the query object if you wish to use a
1345
different query interface instead of CGI.pm.
1346

1347
CGI.pm is only loaded if it is used on a given request.
1348

1349 1350
If you can use an alternative to CGI.pm, it needs to have some compatibility
with the CGI.pm API. For normal use, just having a compatible C<param> method
1351
should be sufficient.
1352

1353
If you use the C<path_info> option to the mode_param() method, then we will call
1354
the C<path_info()> method on the query object.
1355

1356
If you use the C<Dump> method in CGI::Application, we will call the C<Dump> and
1357
C<escapeHTML> methods on the query object.
1358

1359
=head2 Essential Application Methods
1360 1361 1362

The following methods are inherited from CGI::Application, and are
available to be called by your application within your Application
1363 1364
Module. They are called essential because you will use all are most
of them to get any application up and running.  These functions are listed in alphabetical order.
1365

1366
=head3 load_tmpl()
1367

1368 1369 1370 1371
    my $tmpl_obj = $webapp->load_tmpl;
    my $tmpl_obj = $webapp->load_tmpl('some.html');
    my $tmpl_obj = $webapp->load_tmpl( \$template_content );
    my $tmpl_obj = $webapp->load_tmpl( FILEHANDLE );
1372

1373
This method takes the name of a template file, a reference to template data
1374
or a FILEHANDLE and returns an HTML::Template object. If the filename is undefined or missing, CGI::Application will default to trying to use the current run mode name, plus the extension ".html".
1375 1376 1377 1378 1379 1380

If you use the default template naming system, you should also use
L<CGI::Application::Plugin::Forward>, which simply helps to keep the current
name accurate when you pass control from one run mode to another.

( For integration with other template systems
1381 1382
and automated template names, see "Alternatives to load_tmpl() below. )

1383 1384 1385 1386 1387 1388
When you pass in a filename, the HTML::Template->new_file() constructor
is used for create the object.  When you pass in a reference to the template
content, the HTML::Template->new_scalar_ref() constructor is used and
when you pass in a filehandle, the HTML::Template->new_filehandle()
constructor is used.

1389
Refer to L<HTML::Template> for specific usage of HTML::Template.
1390 1391 1392 1393 1394 1395

If tmpl_path() has been specified, load_tmpl() will set the
HTML::Template C<path> option to the path(s) provided.  This further
assists in encapsulating template usage.

The load_tmpl() method will pass any extra parameters sent to it directly to
1396 1397
HTML::Template->new_file() (or new_scalar_ref() or new_filehandle()).
This will allow the HTML::Template object to be further customized:
1398

1399 1400 1401 1402 1403 1404 1405 1406
    my $tmpl_obj = $webapp->load_tmpl('some_other.html',
         die_on_bad_params => 0,
         cache => 1
    );

Note that if you want to pass extra arguments but use the default template
name, you still need to provide a name of C<undef>:

1407
    my $tmpl_obj = $webapp->load_tmpl(undef,
1408 1409 1410 1411
         die_on_bad_params => 0,
         cache => 1
    );

1412 1413 1414 1415 1416 1417
B<Alternatives to load_tmpl()>

If your application requires more specialized behavior than this, you can
always replace it by overriding load_tmpl() by implementing your own
load_tmpl() in your CGI::Application sub-class application module.

1418
First, you may want to check out the template related plugins.
1419 1420 1421 1422 1423

L<CGI::Application::Plugin::TT> focuses just on Template Toolkit integration,
and features pre-and-post features, singleton support and more.

L<CGI::Application::Plugin::Stream> can help if you want to return a stream and
1424
not a file. It features a simple syntax and MIME-type detection.
1425

1426 1427
B<specifying the template class with html_tmpl_class()>

1428 1429 1430 1431 1432 1433
You may specify an API-compatible alternative to L<HTML::Template> by setting
a new C<html_tmpl_class()>:

  $self->html_tmpl_class('HTML::Template::Dumper');

The default is "HTML::Template". The alternate class should
1434 1435 1436 1437 1438
provide at least the following parts of the HTML::Template API:

 $t = $class->new( scalarref => ... );  # If you use scalarref templates
 $t = $class->new( filehandle => ... ); # If you use filehandle templates
 $t = $class->new( filename => ... );
1439
 $t->param(...);
1440

1441 1442
Here's an example case allowing you to precisely test what's sent to your
templates:
1443

1444 1445
    $ENV{CGI_APP_RETURN_ONLY} = 1;
    my $webapp = WebApp->new;
1446
       $webapp->html_tmpl_class('HTML::Template::Dumper');
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
    my $out_str = $webapp->run;
    my $tmpl_href = eval "$out_str";

    # Now Precisely test what would be set to the template
    is ($tmpl_href->{pet_name}, 'Daisy', "Daisy is sent template");

This is a powerful technique because HTML::Template::Dumper loads and considers
the template file that would actually be used. If the 'pet_name' token was missing
in the template, the above test would fail. So, you are testing both your code
and your templates in a much more precise way than using simple regular
expressions to see if the string "Daisy" appeared somewhere on the page.
1458

1459 1460
B<The load_tmpl() callback>

1461
Plugin authors will be interested to know that you can register a callback that
1462
will be executed just before load_tmpl() returns:
1463

1464
  $self->add_callback('load_tmpl',\&your_method);
1465

1466
When C<your_method()> is executed, it will be passed three arguments:
1467 1468

 1. A hash reference of the extra params passed into C<load_tmpl>
1469 1470
 2. Followed by a hash reference to template parameters.
    With both of these, you can modify them by reference to affect
1471 1472
    values that are actually passed to the new() and param() methods of the
    template object.
1473
 3. The name of the template file.
1474

1475
Here's an example stub for a load_tmpl() callback:
1476 1477

    sub my_load_tmpl_callback {
1478
        my ($c, $ht_params, $tmpl_params, $tmpl_file) = @_
1479
        # modify $ht_params or $tmpl_params by reference...
1480 1481
    }

1482
=head3 param()
1483

1484
    $webapp->param('pname', $somevalue);
1485

1486 1487 1488
The param() method provides a facility through which you may set
application instance properties which are accessible throughout
your application.
1489

1490 1491
The param() method may be used in two basic ways.  First, you may use it
to get or set the value of a parameter:
1492

1493 1494
    $webapp->param('scalar_param', '123');
    my $scalar_param_values = $webapp->param('some_param');
1495

1496 1497 1498
Second, when called in the context of an array, with no parameter name
specified, param() returns an array containing all the parameters which
currently exist:
1499

1500
    my @all_params = $webapp->param();
1501

1502 1503
The param() method also allows you to set a bunch of parameters at once
by passing in a hash (or hashref):
1504

1505 1506 1507 1508 1509
    $webapp->param(
        'key1' => 'val1',
        'key2' => 'val2',
        'key3' => 'val3',
    );
1510

1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
The param() method enables a very valuable system for
customizing your applications on a per-instance basis.
One Application Module might be instantiated by different
Instance Scripts.  Each Instance Script might set different values for a
set of parameters.  This allows similar applications to share a common
code-base, but behave differently.  For example, imagine a mail form
application with a single Application Module, but multiple Instance
Scripts.  Each Instance Script might specify a different recipient.
Another example would be a web bulletin boards system.  There could be
multiple boards, each with a different topic and set of administrators.
1521

1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
The new() method provides a shortcut for specifying a number of run-time
parameters at once.  Internally, CGI::Application calls the param()
method to set these properties.  The param() method is a powerful tool for
greatly increasing your application's re-usability.

=head3 query()

    my $q = $webapp->query();
    my $remote_user = $q->remote_user();

This method retrieves the CGI.pm query object which has been created
by instantiating your Application Module.  For details on usage of this
query object, refer to L<CGI>.  CGI::Application is built on the CGI
module.  Generally speaking, you will want to become very familiar
with CGI.pm, as you will use the query object whenever you want to
interact with form data.

When the new() method is called, a CGI query object is automatically created.
If, for some reason, you want to use your own CGI query object, the new()
method supports passing in your existing query object on construction using
the QUERY attribute.

1544 1545
There are a few rare situations where you want your own query object to be
used after your Application Module has already been constructed. In that case
1546 1547 1548 1549
you can pass it to c<query()> like this:

    $webapp->query($new_query_object);
    my $q = $webapp->query(); # now uses $new_query_object
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560

=head3 run_modes()

    # The common usage: an arrayref of run mode names that exactly match subroutine names
    $webapp->run_modes([qw/
        form_display
        form_process
    /]);

   # With a hashref, use a different name or a code ref
   $webapp->run_modes(
1561
           'mode1' => 'some_sub_by_name',
1562 1563 1564 1565
           'mode2' => \&some_other_sub_by_ref
    );

This accessor/mutator specifies the dispatch table for the
1566 1567
application states, using the syntax examples above. It returns
the dispatch table as a hash.
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611

The run_modes() method may be called more than once.  Additional values passed
into run_modes() will be added to the run modes table.  In the case that an
existing run mode is re-defined, the new value will override the existing value.
This behavior might be useful for applications which are created via inheritance
from another application, or some advanced application which modifies its
own capabilities based on user input.

The run() method uses the data in this table to send the application to the
correct function as determined by reading the CGI parameter specified by
mode_param() (defaults to 'rm' for "Run Mode").  These functions are referred
to as "run mode methods".

The hash table set by this method is expected to contain the mode
name as a key.  The value should be either a hard reference (a subref)
to the run mode method which you want to be called when the application enters
the specified run mode, or the name of the run mode method to be called:

    'mode_name_by_ref'  => \&mode_functio