~ubuntu-branches/ubuntu/edgy/libapache2-mod-perl2/edgy

« back to all changes in this revision

Viewing changes to docs/user/coding/coding.pod

  • Committer: Bazaar Package Importer
  • Author(s): Adam Conrad
  • Date: 2004-08-19 06:23:48 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20040819062348-jxl4koqbtvgm8v2t
Tags: 1.99.14-4
Remove the LFS CFLAGS, and build-dep against apache2-*-dev (>= 2.0.50-10)
as we're backing out of the apache2/apr ABI transition.

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
C<L<ModPerl::MethodLookup|docs::2.0::api::ModPerl::MethodLookup>> can
20
20
be used to find out which modules need to be used.
21
21
 
 
22
 
 
23
=head1 Techniques
 
24
 
 
25
 
 
26
 
 
27
=head2 Method Handlers
 
28
 
 
29
In mod_perl 2.0 method handlers are declared using the C<method>
 
30
attribute:
 
31
 
 
32
  package Bird;
 
33
  @ISA = qw(Eagle);
 
34
  
 
35
  sub handler : method {
 
36
      my($class, $r) = @_;
 
37
      ...;
 
38
  }
 
39
 
 
40
See the I<attributes> manpage.
 
41
 
 
42
If C<Class-E<gt>method> syntax is used for a C<Perl*Handler>, the
 
43
C<:method> attribute is not required.
 
44
 
 
45
META: need to port the method handlers document from mp1 guide, may be
 
46
keep it as a separate document. Meanwhile refer to L<that
 
47
document|docs::1.0::guide::method_handlers>, though L<replace the C<$$> 
 
48
prototype with the C<:method> attribute
 
49
|docs::2.0::user::porting::compat/Method_Handlers>.
 
50
 
 
51
 
 
52
=head2 Cleaning up
 
53
 
 
54
It's possible to arrange for cleanups to happen at the end of various
 
55
phases. One can't rely on C<END> blocks to do the job, since these
 
56
L<don't get executed|/C_END__Blocks> until the interpreter quits, with
 
57
an exception to the
 
58
L<Registry|docs::2.0::api::ModPerl::Registry/C_END__Blocks> handlers.
 
59
 
 
60
Module authors needing to run cleanups after each HTTP request, should
 
61
use
 
62
C<L<PerlCleanupHandler|docs::2.0::user::handlers::http/PerlCleanupHandler>>.
 
63
 
 
64
Module authors needing to run cleanups at other times can always
 
65
register a cleanup callback via
 
66
C<L<cleanup_register|docs::2.0::api::APR::Pool/C_cleanup_register_>>
 
67
on the pool object of choice. Here are some examples of its usage:
 
68
 
 
69
To run something at the server shutdown and restart use
 
70
C<$s-E<gt>pool-E<gt>cleanup_register()> in F<startup.pl>:
 
71
 
 
72
  #PerlRequire startup.pl
 
73
  use Apache::ServerUtil ();
 
74
  use APR::Pool ();
 
75
  
 
76
  warn "parent pid is $$\n";
 
77
  my $pool = Apache->server->pool;
 
78
  $pool->cleanup_register(\&cleanup);
 
79
  sub cleanup { warn "server cleanup in $$\n" }
 
80
 
 
81
This is usually useful when some server-wide cleanup should be
 
82
performed when the server is stopped or restarted.
 
83
 
 
84
To run a cleanup at the end of each connection phase, assign a cleanup
 
85
callback to the connection pool object:
 
86
 
 
87
  use Apache::Connection ();
 
88
  use APR::Pool ();
 
89
  
 
90
  my $pool = $c->pool;
 
91
  $pool->cleanup_register(\&my_cleanup);
 
92
  sub my_cleanup { ... }
 
93
 
 
94
You can also create your own pool object, register a cleanup callback
 
95
and it'll be called when the object is destroyed:
 
96
 
 
97
  use APR::Pool ();
 
98
  
 
99
  {
 
100
      my @args = 1..3;
 
101
      my $pool = APR::Pool->new;
 
102
      $pool->cleanup_register(\&cleanup, \@args);
 
103
  }
 
104
  
 
105
  sub cleanup {
 
106
      my @args = @{ +shift };
 
107
      warn "cleanup was called with args: @args";
 
108
  }
 
109
 
 
110
In this example the cleanup callback gets called, when C<$pool> goes
 
111
out of scope and gets destroyed. This is very similar to OO C<DESTROY>
 
112
method.
 
113
 
 
114
 
22
115
=head1 Goodies Toolkit
23
116
 
24
117
=head2 Environment Variables
46
139
  use constant MP2 => ($mod_perl::VERSION >= 1.99);
47
140
  # die "I want mod_perl 2.0!" unless MP2;
48
141
 
49
 
=item *
50
 
 
51
 
C<$ENV{GATEWAY_INTERFACE}> - is set to C<CGI-Perl/1.1> for
52
 
compatibility with mod_perl 1.0. This variable is deprecated in
53
 
mod_perl 2.0. Use C<$ENV{MOD_PERL}> instead.
54
 
 
55
142
=back
56
143
 
57
144
mod_perl passes (exports) the following shell environment variables
177
264
In the following sections we discuss the specifics of Apache behavior
178
265
relevant to mod_perl developers.
179
266
 
180
 
=head2 Sending HTTP Response Headers
 
267
=head2 HTTP Response Headers
 
268
 
 
269
=head3 Generating HTTP Response Headers
 
270
 
 
271
The best approach for generating HTTP response headers is by using the
 
272
L<mod_perl API|docs::2.0::api::Apache::RequestRec>. Some common
 
273
headers have dedicated methods, others are set by manipulating the
 
274
C<L<headers_out|docs::2.0::api::Apache::RequestRec/C_headers_out_>>
 
275
table directly.
 
276
 
 
277
For example to set the I<Content-type> header you should call
 
278
C<L<$r-E<gt>content_type|docs::2.0::api::Apache::RequestRec/C_content_type_>>:
 
279
 
 
280
  use Apache::RequestRec ();
 
281
  $r->content_type('text/html');
 
282
 
 
283
To C<L<set|docs::2.0::api::APR::Table/C_set_>> a custom header
 
284
I<My-Header> you should call:
 
285
 
 
286
  use Apache::RequestRec ();
 
287
  use APR::Table;
 
288
  $r->headers_out->set(My-Header => "SomeValue");
 
289
 
 
290
If you are inside a registry script L<you can still
 
291
access|docs::2.0::user::coding::coding/Getting_the_C__r__Object> the
 
292
C<L<Apache::RequestRec|docs::2.0::api::Apache::RequestRec>> object.
 
293
 
 
294
Howerever you can choose a slower method of generating headers by just
 
295
printing them out before printing any response. This will work only if
 
296
C<L<PerlOptions
 
297
+ParseHeaders|docs::2.0::user::config::config/C_ParseHeaders_>> is
 
298
in effect. For example:
 
299
 
 
300
   print "Content-type: text/html\n";
 
301
   print "My-Header: SomeValue\n";
 
302
   print "\n";
 
303
 
 
304
This method is slower since Apache needs to parse the text to identify
 
305
certain headers it needs to know about. It also has several
 
306
limitations which we will now discuss.
 
307
 
 
308
When using this approach you must make sure that the C<STDOUT>
 
309
filehandle is not set to flush the data after each print (which is set
 
310
by the value of a special perl variable C<$|>). Here we assume that
 
311
STDOUT is the currently C<select()>ed filehandle and C<$|> affects it.
 
312
 
 
313
For example this code won't work:
 
314
 
 
315
   local $| = 1;
 
316
   print "Content-type: text/html\n";
 
317
   print "My-Header: SomeValue\n";
 
318
   print "\n";
 
319
 
 
320
Having a true C<$|> causes the first print() call to flush its data
 
321
immediately, which is sent to the internal HTTP header parser, which
 
322
will fail since it won't see the terminating C<"\n\n">. One solution
 
323
is to make sure that STDOUT won't flush immediately, like so:
 
324
 
 
325
   local $| = 0;
 
326
   print "Content-type: text/html\n";
 
327
   print "My-Header: SomeValue\n";
 
328
   print "\n";
 
329
 
 
330
Notice that we C<local()>ize that change, so it L<won't affect any
 
331
other
 
332
code|docs::general::perl_reference::perl_reference/The_Scope_of_the_Special_Perl_Variables>.
 
333
 
 
334
If you send headers line by line and their total length is bigger than
 
335
8k, you will have the header parser problem again, since mod_perl will
 
336
flush data when the 8k buffer gets full. In which case the solution is
 
337
not to print the headers one by one, but to buffer them all in a
 
338
variable and then print the whole set at once.
 
339
 
 
340
Notice that you don't have any of these problems with mod_cgi, because
 
341
it ignores any of the flush attempts by Perl. mod_cgi simply opens a
 
342
pipe to the external process and reads any output sent from that
 
343
process at once.
 
344
 
 
345
If you use C<$r> to set headers as explained at the beginning of this
 
346
section, you won't encounter any of these problems.
 
347
 
 
348
Finally, If you don't want Apache to send its own headers and you want
 
349
to send your own set of headers (non-parsed headers handlers) use
 
350
explain the
 
351
C<L<$r-E<gt>assbackwards|docs::2.0::api::Apache::RequestRec/C_assbackwards_>>
 
352
method. Notice that registry handlers will do that for you if the
 
353
script's name start with the C<nph-> prefix.
 
354
 
 
355
 
 
356
 
 
357
 
 
358
=head3 Forcing HTTP Response Headers Out
181
359
 
182
360
Apache 2.0 doesn't provide a method to force HTTP response headers
183
361
sending (what used to be done by C<send_http_header()> in Apache
184
362
1.3). HTTP response headers are sent as soon as the first bits of the
185
363
response body are seen by the special core output filter that
186
 
generates these headers. When the response handler send the first
 
364
generates these headers. When the response handler sends the first
187
365
chunks of body it may be cached by the mod_perl internal buffer or
188
366
even by some of the output filters. The response handler needs to
189
 
flush in order to tell all the components participating in the sending
190
 
of the response to pass the data out.
 
367
flush the output in order to tell all the components participating in
 
368
the sending of the response to pass the data out.
191
369
 
192
370
For example if the handler needs to perform a relatively long-running
193
371
operation (e.g. a slow db lookup) and the client may timeout if it
204
382
  }
205
383
 
206
384
If this doesn't work, check whether you have configured any
207
 
third-party output filters for the resource in question. Improperly
208
 
written filter may ignore the orders to flush the data.
209
 
 
210
 
META: add a link to the notes on how to write well-behaved filters
211
 
at handlers/filters
 
385
third-party output filters for the resource in question. L<Improperly
 
386
written
 
387
filter|docs::2.0::user::handlers::filters/Writing_Well_Behaving_Filters>
 
388
may ignore the command to flush the data.
 
389
 
 
390
 
 
391
 
 
392
 
212
393
 
213
394
=head2 Sending HTTP Response Body
214
395
 
220
401
the issues is that the HTTP response filters are not setup before the
221
402
response phase.
222
403
 
 
404
 
 
405
 
 
406
 
223
407
=head1 Perl Specifics in the mod_perl Environment
224
408
 
225
409
In the following sections we discuss the specifics of Perl behavior
226
410
under mod_perl.
227
411
 
 
412
 
 
413
 
 
414
 
 
415
=head2 C<BEGIN> Blocks
 
416
 
 
417
Perl executes C<BEGIN> blocks as soon as possible, at the time of
 
418
compiling the code. The same is true under mod_perl. However, since
 
419
mod_perl normally only compiles scripts and modules once, either in
 
420
the parent server (at the server startup) or once per-child (on the
 
421
first request using a module), C<BEGIN> blocks in that code will only
 
422
be run once.  As the C<perlmod> manpage explains, once a C<BEGIN>
 
423
block has run, it is immediately undefined. In the mod_perl
 
424
environment, this means that C<BEGIN> blocks will not be run during
 
425
the response to an incoming request unless that request happens to be
 
426
the one that causes the compilation of the code, i.e. if it wasn't
 
427
loaded yet.
 
428
 
 
429
C<BEGIN> blocks in modules and files pulled in via C<require()> or
 
430
C<use()> will be executed:
 
431
 
 
432
=over 4
 
433
 
 
434
=item *
 
435
 
 
436
Only once, if pulled in by the parent process at the server startup.
 
437
 
 
438
=item *
 
439
 
 
440
Once per each child process or Perl interpreter if not pulled in by
 
441
the parent process.
 
442
 
 
443
=item *
 
444
 
 
445
An additional time, once per each child process or Perl interpreter if
 
446
the module is reloaded off disk again via
 
447
C<L<Apache::Reload|docs::2.0::api::Apache::Reload>>.
 
448
 
 
449
=item *
 
450
 
 
451
Unpredictable if you fiddle with C<%INC> yourself.
 
452
 
 
453
=back
 
454
 
 
455
The C<BEGIN> blocks behavior is different in
 
456
C<L<ModPerl::Registry|docs::2.0::api::ModPerl::Registry/C_BEGIN__Blocks>>
 
457
and
 
458
C<L<ModPerl::PerlRun|docs::2.0::api::ModPerl::PerlRun/C_BEGIN__Blocks>>
 
459
handlers, and their subclasses.
 
460
 
 
461
 
 
462
 
 
463
 
 
464
 
 
465
=head2 C<CHECK> and C<INIT> Blocks
 
466
 
 
467
C<CHECK> and C<INIT> blocks run when the source code compilation is
 
468
complete, but before the program starts. C<CHECK> can mean
 
469
"checkpoint" or "double-check" or even just "stop". C<INIT> stands for
 
470
"initialization". The difference is subtle; C<CHECK> blocks are run
 
471
just after the compilation ends, C<INIT> just before the runtime
 
472
begins. (Hence the C<-c> command-line perl option runs C<CHECK> blocks
 
473
but not C<INIT> blocks.)
 
474
 
 
475
Perl only calls these blocks during I<perl_parse()>, which mod_perl
 
476
calls once at startup time. Under threaded mpm, these blocks will be
 
477
called once per C<L<parent perl interpreter
 
478
startup|docs::2.0::user::config::config/C_Parent_>>. Therefore
 
479
C<CHECK> and C<INIT> blocks don't work after the server is started,
 
480
for the same reason these code samples don't work:
 
481
 
 
482
  % perl -e 'eval qq(CHECK { print "ok\n" })'
 
483
  % perl -e 'eval qq(INIT  { print "ok\n" })'
 
484
 
 
485
 
 
486
 
 
487
 
 
488
=head2 C<END> Blocks
 
489
 
 
490
As the C<perlmod> manpage explains, an C<END> block is executed as
 
491
late as possible, that is, when the interpreter exits. So for example
 
492
mod_cgi will run its C<END> blocks on each invocation, since on every
 
493
invocation it starts a new interpreter and then kills it when the
 
494
request processing is done.
 
495
 
 
496
In the mod_perl environment, the interpreter does not exit after
 
497
serving a single request (unless it is configured to do so) and hence
 
498
it will run its C<END> blocks only when it exits, which usually
 
499
happens during the server shutdown, but may also happen earlier than
 
500
that (e.g. a process exits because it has served a
 
501
C<MaxRequestsPerChild> number of requests).
 
502
 
 
503
mod_perl does L<make a special
 
504
case|docs::2.0::api::ModPerl::Registry/C_END__Blocks>
 
505
for scripts running under
 
506
C<L<ModPerl::Registry|docs::2.0::api::ModPerl::Registry>> and friends.
 
507
 
 
508
The L<Cleaning up|/Cleaning_up> section explains how to deal with
 
509
cleanups for non-Registry handlers.
 
510
 
 
511
C<L<ModPerl::Global|docs::2.0::api::ModPerl::Global>> API:
 
512
C<L<special_list_register|docs::2.0::api::ModPerl::Global/C_special_list_register_>>,
 
513
C<L<special_list_call|docs::2.0::api::ModPerl::Global/C_special_list_call_>>
 
514
and
 
515
C<L<special_list_clear|docs::2.0::api::ModPerl::Global/C_special_list_clear_>>,
 
516
internally used by registry handlers, can be used to run C<END> blocks
 
517
at arbitrary times.
 
518
 
 
519
 
228
520
=head2 Request-localized Globals
229
521
 
230
522
mod_perl 2.0 provides two types of C<SetHandler> handlers:
250
542
localize all special Perl variables so the local changes won't affect
251
543
other handlers.
252
544
 
253
 
=head2 exit()
 
545
 
 
546
 
 
547
=head2 C<exit>
254
548
 
255
549
In the normal Perl code exit() is used to stop the program flow and
256
550
exit the Perl interpreter. However under mod_perl we only want the
258
552
 
259
553
You should take no action if your code includes exit() calls and it's
260
554
OK to continue using them. mod_perl worries to override the exit()
261
 
function with its own version which stops the program flow, and
262
 
performs all the necessary cleanups, but doesn't kill the server. This
263
 
is done by overriding:
 
555
function with L<its own version|docs::2.0::api::ModPerl::Util/C_exit_>
 
556
which stops the program flow, and performs all the necessary cleanups,
 
557
but doesn't kill the server. This is done by overriding:
264
558
 
265
559
  *CORE::GLOBAL::exit = \&ModPerl::Util::exit;
266
560
 
270
564
You can still call C<CORE::exit> to kill the interpreter, again if you
271
565
know what you are doing.
272
566
 
 
567
One caveat is when C<exit> is called inside C<eval> -- L<the
 
568
ModPerl::Util::exit
 
569
documentation|docs::2.0::api::ModPerl::Util/C_exit_> explains how to
 
570
deal with this situation.
 
571
 
 
572
 
 
573
 
 
574
 
 
575
 
 
576
 
 
577
=head1 C<ModPerl::Registry> Handlers Family
 
578
 
 
579
=head2 A Look Behind the Scenes
 
580
 
 
581
If you have a CGI script F<test.pl>:
 
582
 
 
583
  #!/usr/bin/perl
 
584
  print "Content-type: text/plain\n\n";
 
585
  print "Hello";
 
586
 
 
587
a typical registry family handler turns it into something like:
 
588
 
 
589
  package foo_bar_baz;
 
590
  sub handler {
 
591
      local $0 = "/full/path/to/test.pl";
 
592
  #line 1 test.pl
 
593
      #!/usr/bin/perl
 
594
      print "Content-type: text/plain\n\n";
 
595
      print "Hello";
 
596
  }
 
597
 
 
598
Turning it into an almost full-fledged mod_perl handler. The only
 
599
difference is that it handles the return status for you. (META: more
 
600
details on return status needed.)
 
601
 
 
602
It then executes it as:
 
603
 
 
604
  foo_bar_baz::handler($r);
 
605
 
 
606
passing the C<L<$r|docs::2.0::api::Apache::RequestRec>> object as the
 
607
only argument to the C<handler()> function.
 
608
 
 
609
Depending on the used registry handler the package is made of the file
 
610
path, the uri or anything else. Check the handler's documentation to
 
611
learn which method is used.
 
612
 
 
613
 
 
614
 
 
615
=head2 Getting the C<$r> Object
 
616
 
 
617
As explained in L<A Look Behind the Scenes|/A_Look_Behind_the_Scenes>
 
618
the C<$r> object is always passed to the registry script's special
 
619
function C<handler> as the first and the only argument, so you can get
 
620
this object by accessing C<@_>, since:
 
621
 
 
622
  my $r = shift;
 
623
  print "Content-type: text/plain\n\n";
 
624
  print "Hello";
 
625
 
 
626
is turned into:
 
627
 
 
628
  sub handler {
 
629
      my $r = shift;
 
630
      print "Content-type: text/plain\n\n";
 
631
      print "Hello";
 
632
  }
 
633
 
 
634
behind the scenes. Now you can use C<$r> to call various mod_perl
 
635
methods, e.g. rewriting the script as:
 
636
 
 
637
  my $r = shift;
 
638
  $r->content_type('text/plain');
 
639
  $r->print();
 
640
 
 
641
If you are deep inside some code and can't get to the entry point to
 
642
reach for C<$r>, you can use
 
643
C<L<Apache-E<gt>request|docs::2.0::api::Apache::RequestUtil/C_request_>>.
 
644
 
 
645
 
 
646
 
 
647
 
 
648
 
 
649
 
 
650
 
 
651
 
 
652
 
 
653
 
 
654
 
273
655
 
274
656
=head1 Threads Coding Issues Under mod_perl
275
657