factor dispatcher out into Web::Dispatch
[catagits/Web-Simple.git] / lib / Web / Simple.pm
1 package Web::Simple;
2
3 use strict;
4 use warnings FATAL => 'all';
5 use 5.008;
6
7 our $VERSION = '0.004';
8
9 sub setup_all_strictures {
10   strict->import;
11   warnings->import(FATAL => 'all');
12 }
13
14 sub setup_dispatch_strictures {
15   setup_all_strictures();
16   warnings->unimport('syntax');
17   warnings->import(FATAL => qw(
18     ambiguous bareword digit parenthesis precedence printf
19     prototype qw reserved semicolon
20   ));
21 }
22
23 sub import {
24   setup_dispatch_strictures();
25   my ($class, $app_package) = @_;
26   $class->_export_into($app_package||caller);
27 }
28
29 sub _export_into {
30   my ($class, $app_package) = @_;
31   {
32     no strict 'refs';
33     *{"${app_package}::dispatch"} = sub (&) {
34       $app_package->_setup_dispatcher($_[0]);
35     };
36     *{"${app_package}::response_filter"} = sub (&) {
37       $app_package->_construct_response_filter($_[0]);
38     };
39     *{"${app_package}::redispatch_to"} = sub {
40       $app_package->_construct_redispatch($_[0]);
41     };
42     *{"${app_package}::default_config"} = sub {
43       $app_package->_setup_default_config(@_);
44     };
45     *{"${app_package}::PSGI_ENV"} = sub () { -1 };
46     *{"${app_package}::self"} = \${"${app_package}::self"};
47     require Web::Simple::Application;
48     unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
49   }
50   (my $name = $app_package) =~ s/::/\//g;
51   $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
52 }
53
54 =head1 NAME
55
56 Web::Simple - A quick and easy way to build simple web applications
57
58 =head1 WARNING
59
60 This is really quite new. If you're reading this on CPAN, it means the stuff
61 that's here we're probably happy with. But only probably. So we may have to
62 change stuff. And if you're reading this from git, come check with irc.perl.org
63 #web-simple that we're actually sure we're going to keep anything that's
64 different from the CPAN version.
65
66 If we do find we have to change stuff we'll add to the
67 L<CHANGES BETWEEN RELEASES> section explaining how to switch your code across
68 to the new version, and we'll do our best to make it as painless as possible
69 because we've got Web::Simple applications too. But we can't promise not to
70 change things at all. Not yet. Sorry.
71
72 =head1 SYNOPSIS
73
74   #!/usr/bin/perl
75
76   use Web::Simple 'HelloWorld';
77
78   {
79     package HelloWorld;
80
81     dispatch {
82       sub (GET) {
83         [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
84       },
85       sub () {
86         [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
87       }
88     };
89   }
90
91   HelloWorld->run_if_script;
92
93 If you save this file into your cgi-bin as hello-world.cgi and then visit
94
95   http://my.server.name/cgi-bin/hello-world.cgi/
96
97 you'll get the "Hello world!" string output to your browser. For more complex
98 examples and non-CGI deployment, see below. To get help with Web::Simple,
99 please connect to the irc.perl.org IRC network and join #web-simple.
100
101 =head1 WHY?
102
103 Web::Simple was originally written to form part of my Antiquated Perl talk for
104 Italian Perl Workshop 2009, but in writing the bloggery example I realised
105 that having a bare minimum system for writing web applications that doesn't
106 drive me insane was rather nice and decided to spend my attempt at nanowrimo
107 for 2009 improving and documenting it to the point where others could use it.
108
109 The philosophy of Web::Simple is to keep to an absolute bare minimum, for
110 everything. It is not designed to be used for large scale applications;
111 the L<Catalyst> web framework already works very nicely for that and is
112 a far more mature, well supported piece of software.
113
114 However, if you have an application that only does a couple of things, and
115 want to not have to think about complexities of deployment, then Web::Simple
116 might be just the thing for you.
117
118 The Antiquated Perl talk can be found at L<http://www.shadowcat.co.uk/archive/conference-video/>.
119
120 =head1 DESCRIPTION
121
122 The only public interface the Web::Simple module itself provides is an
123 import based one -
124
125   use Web::Simple 'NameOfApplication';
126
127 This imports 'strict' and 'warnings FATAL => "all"' into your code as well,
128 so you can skip the usual
129
130   use strict;
131   use warnings;
132
133 provided you 'use Web::Simple' at the top of the file. Note that we turn
134 on *fatal* warnings so if you have any warnings at any point from the file
135 that you did 'use Web::Simple' in, then your application will die. This is,
136 so far, considered a feature.
137
138 Calling the import also makes NameOfApplication isa Web::Simple::Application
139 - i.e. does the equivalent of
140
141   {
142     package NameOfApplication;
143     use base qw(Web::Simple::Application);
144   }
145
146 It also exports the following subroutines:
147
148   default_config(
149     key => 'value',
150     ...
151   );
152
153   dispatch { sub (...) { ... }, ... };
154
155   response_filter { ... };
156
157   redispatch_to '/somewhere';
158
159   subdispatch sub (...) { ... }
160
161 and creates a $self global variable in your application package, so you can
162 use $self in dispatch subs without violating strict (Web::Simple::Application
163 arranges for dispatch subroutines to have the correct $self in scope when
164 this happens).
165
166 Finally, import sets
167
168   $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
169
170 so that perl will not attempt to load the application again even if
171
172   require NameOfApplication;
173
174 is encountered in other code.
175
176 =head1 DISPATCH STRATEGY
177
178 =head2 Examples
179
180  dispatch {
181    # matches: GET /user/1.htm?show_details=1
182    #          GET /user/1.htm
183    sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
184      my ($self, $user_id, $show_details) = @_;
185      ...
186    },
187    # matches: POST /user?username=frew
188    #          POST /user?username=mst&first_name=matt&last_name=trout
189    sub (POST + /user + ?username=&*) {
190       my ($self, $username, $misc_params) = @_;
191      ...
192    },
193    # matches: DELETE /user/1/friend/2
194    sub (DELETE + /user/*/friend/*) {
195      my ($self, $user_id, $friend_id) = @_;
196      ...
197    },
198    # matches: PUT /user/1?first_name=Matt&last_name=Trout
199    sub (PUT + /user/* + ?first_name~&last_name~) {
200      my ($self, $user_id, $first_name, $last_name) = @_;
201      ...
202    },
203    sub (/user/*/...) {
204       my $user_id = $_[1];
205       subdispatch sub {
206          [
207             # matches: PUT /user/1/role/1
208             sub (PUT + /role/*) {
209               my $role_id = $_[1];
210               ...
211             },
212             # matches: DELETE /user/1/role/1
213             sub (DELETE + /role/*) {
214               my $role_id = $_[1];
215               ...
216             },
217          ];
218       }
219    },
220  }
221
222 =head2 Description of the dispatcher object
223
224 Web::Simple::Dispatcher objects have three components:
225
226 =over 4
227
228 =item * match - an optional test if this dispatcher matches the request
229
230 =item * call - a routine to call if this dispatcher matches (or has no match)
231
232 =item * next - the next dispatcher to call
233
234 =back
235
236 When a dispatcher is invoked, it checks its match routine against the
237 request environment. The match routine may provide alterations to the
238 request as a result of matching, and/or arguments for the call routine.
239
240 If no match routine has been provided then Web::Simple treats this as
241 a success, and supplies the request environment to the call routine as
242 an argument.
243
244 Given a successful match, the call routine is now invoked in list context
245 with any arguments given to the original dispatch, plus any arguments
246 provided by the match result.
247
248 If this routine returns (), Web::Simple treats this identically to a failure
249 to match.
250
251 If this routine returns a Web::Simple::Dispatcher, the environment changes
252 are merged into the environment and the new dispatcher's next pointer is
253 set to our next pointer.
254
255 If this routine returns anything else, that is treated as the end of dispatch
256 and the value is returned.
257
258 On a failed match, Web::Simple invokes the next dispatcher with the same
259 arguments and request environment passed to the current one. On a successful
260 match that returned a new dispatcher, Web::Simple invokes the new dispatcher
261 with the same arguments but the modified request environment.
262
263 =head2 How Web::Simple builds dispatcher objects for you
264
265 In the case of the Web::Simple L</dispatch> export the match is constructed
266 from the subroutine prototype - i.e.
267
268   sub (<match specification>) {
269     <call code>
270   }
271
272 and the 'next' pointer is populated with the next element of the array,
273 expect for the last element, which is given a next that will throw a 500
274 error if none of your dispatchers match. If you want to provide something
275 else as a default, a routine with no match specification always matches, so -
276
277   sub () {
278     [ 404, [ 'Content-type', 'text/plain' ], [ 'Error: Not Found' ] ]
279   }
280
281 will produce a 404 result instead of a 500 by default. You can also override
282 the L<Web::Simple::Application/_build_final_dispatcher> method in your app.
283
284 Note that the code in the subroutine is executed as a -method- on your
285 application object, so if your match specification provides arguments you
286 should unpack them like so:
287
288   sub (<match specification>) {
289     my ($self, @args) = @_;
290     ...
291   }
292
293 =head2 Web::Simple match specifications
294
295 =head3 Method matches
296
297   sub (GET) {
298
299 A match specification beginning with a capital letter matches HTTP requests
300 with that request method.
301
302 =head3 Path matches
303
304   sub (/login) {
305
306 A match specification beginning with a / is a path match. In the simplest
307 case it matches a specific path. To match a path with a wildcard part, you
308 can do:
309
310   sub (/user/*) {
311     $self->handle_user($_[1])
312
313 This will match /user/<anything> where <anything> does not include a literal
314 / character. The matched part becomes part of the match arguments. You can
315 also match more than one part:
316
317   sub (/user/*/*) {
318     my ($self, $user_1, $user_2) = @_;
319
320   sub (/domain/*/user/*) {
321     my ($self, $domain, $user) = @_;
322
323 and so on. To match an arbitrary number of parts, use -
324
325   sub (/page/**) {
326
327 This will result in an element per /-separated part so matched. Note that
328 you can do
329
330   sub (/page/**/edit) {
331
332 to match an arbitrary number of parts up to but not including some final
333 part.
334
335 Finally,
336
337   sub (/foo/...) {
338
339 will match /foo/ on the beginning of the path -and- strip it, much like
340 .html strips the extension. This is designed to be used to construct
341 nested dispatch structures, but can also prove useful for having e.g. an
342 optional language specification at the start of a path.
343
344 Note that the '...' is a "maybe something here, maybe not" so the above
345 specification will match like this:
346
347   /foo         # no match
348   /foo/        # match and strip path to '/'
349   /foo/bar/baz # match and strip path to '/bar/baz'
350
351 =head3 Extension matches
352
353   sub (.html) {
354
355 will match and strip .html from the path (assuming the subroutine itself
356 returns something, of course). This is normally used for rendering - e.g.
357
358   sub (.html) {
359     response_filter { $self->render_html($_[1]) }
360   }
361
362 Additionally,
363
364   sub (.*) {
365
366 will match any extension and supplies the stripped extension as a match
367 argument.
368
369 =head3 Query and body parameter matches
370
371 Query and body parameters can be match via
372
373   sub (?<param spec>) { # match URI query
374   sub (%<param spec>) { # match body params
375
376 The body is only matched if the content type is
377 application/x-www-form-urlencoded (note this means that Web::Simple does
378 not yet handle uploads; this will be addressed in a later release).
379
380 The param spec is elements of one of the following forms -
381
382   param~        # optional parameter
383   param=        # required parameter
384   @param~       # optional multiple parameter
385   @param=       # required multiple parameter
386   :param~       # optional parameter in hashref
387   :param=       # required parameter in hashref
388   :@param~      # optional multiple in hashref
389   :@param=      # required multiple in hashref
390   *             # include all other parameters in hashref
391   @*            # include all other parameters as multiple in hashref
392
393 separated by the & character. The arguments added to the request are
394 one per non-:/* parameter (scalar for normal, arrayref for multiple),
395 plus if any :/* specs exist a hashref containing those values.
396
397 So, to match a page parameter with an optional order_by parameter one
398 would write:
399
400   sub (?page=&order_by~) {
401     my ($self, $page, $order_by) = @_;
402     return unless $page =~ /^\d+$/;
403     $page ||= 'id';
404     response_filter {
405       $_[1]->search_rs({}, $p);
406     }
407   }
408
409 to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
410
411 Note that if a parameter is specified as single and multiple values are found,
412 the last one will be used.
413
414 To get all parameters as a hashref of arrayrefs, write:
415
416   sub(?@*) {
417     my ($self, $params) = @_;
418     ...
419
420 To get two parameters as a hashref, write:
421
422   sub(?:user~&:domain~) {
423     my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
424
425 You can also mix these, so:
426
427   sub (?foo=&@bar~&:coffee=&@*) {
428      my ($self, $foo, $bar, $params);
429
430 where $bar is an arrayref (possibly an empty one), and $params contains
431 arrayref values for all parameters -not- mentioned and a scalar value for
432 the 'coffee' parameter.
433
434 =head3 Combining matches
435
436 Matches may be combined with the + character - e.g.
437
438   sub (GET + /user/*) {
439
440 to create an AND match. They may also be combined withe the | character - e.g.
441
442   sub (GET|POST) {
443
444 to create an OR match. Matches can be nested with () - e.g.
445
446   sub ((GET|POST) + /user/*) {
447
448 and negated with ! - e.g.
449
450   sub (!/user/foo + /user/*) {
451
452 ! binds to the immediate rightmost match specification, so if you want
453 to negate a combination you will need to use
454
455   sub ( !(POST|PUT|DELETE) ) {
456
457 and | binds tighter than +, so
458
459   sub ((GET|POST) + /user/*) {
460
461 and
462
463   sub (GET|POST + /user/*) {
464
465 are equivalent, but
466
467   sub ((GET + .html) | (POST + .html)) {
468
469 and
470
471   sub (GET + .html | POST + .html) {
472
473 are not - the latter is equivalent to
474
475   sub (GET + (.html|POST) + .html) {
476
477 which will never match.
478
479 =head3 Whitespace
480
481 Note that for legibility you are permitted to use whitespace -
482
483   sub (GET + /user/*) {
484
485 but it will be ignored. This is because the perl parser strips whitespace
486 from subroutine prototypes, so this is equivalent to
487
488   sub (GET+/user/*) {
489
490 =head3 Accessing the PSGI env hash
491
492 To gain the benefit of using some middleware, specifically
493 Plack::Middleware::Session access to the ENV hash is needed. This is provided
494 in arguments to the dispatched handler. You can access this hash with the
495 exported +PSGI_ENV constant.
496
497     sub (GET + /foo + ?some_param=) {
498         my($self, $some_param, $env) = @_[0, 1, +PSGI_ENV];
499
500 =head1 EXPORTED SUBROUTINES
501
502 =head2 default_config
503
504   default_config(
505     one_key => 'foo',
506     another_key => 'bar',
507   );
508
509   ...
510
511   $self->config->{one_key} # 'foo'
512
513 This creates the default configuration for the application, by creating a
514
515   sub _default_config {
516      return (one_key => 'foo', another_key => 'bar');
517   }
518
519 in the application namespace when executed. Note that this means that
520 you should only run default_config once - calling it a second time will
521 cause an exception to be thrown.
522
523 =head2 dispatch
524
525   dispatch {
526     sub (GET) {
527       [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
528     },
529     sub () {
530       [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
531     }
532   };
533
534 The dispatch subroutine calls NameOfApplication->_setup_dispatcher with
535 the return value of the block passed to it, which then creates your Web::Simple
536 application's dispatcher from these subs. The prototype of each subroutine
537 is expected to be a Web::Simple dispatch specification (see
538 L</DISPATCH SPECIFICATIONS> below for more details), and the body of the
539 subroutine is the code to execute if the specification matches.
540
541 Each dispatcher is given the dispatcher constructed from the next subroutine
542 returned as its next dispatcher, except for the final subroutine, which
543 is given the return value of NameOfApplication->_build_final_dispatcher
544 as its next dispatcher (by default this returns a 500 error response).
545
546 See L</DISPATCH STRATEGY> below for details on how the Web::Simple dispatch
547 system uses the return values of these subroutines to determine how to
548 continue, alter or abort dispatch.
549
550 Note that _setup_dispatcher creates a
551
552   sub _dispatcher {
553     return <root dispatcher object here>;
554   }
555
556 method in your class so as with default_config, calling dispatch a second time
557 will result in an exception.
558
559 =head2 response_filter
560
561   response_filter {
562     # Hide errors from the user because we hates them, preciousss
563     if (ref($_[1]) eq 'ARRAY' && $_[1]->[0] == 500) {
564       $_[1] = [ 200, @{$_[1]}[1..$#{$_[1]}] ];
565     }
566     return $_[1];
567   };
568
569 The response_filter subroutine is designed for use inside dispatch subroutines.
570
571 It creates and returns a special dispatcher that always matches, and calls
572 the block passed to it as a filter on the result of running the rest of the
573 current dispatch chain.
574
575 Thus the filter above runs further dispatch as normal, but if the result of
576 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
577 response without altering the headers or body.
578
579 =head2 redispatch_to
580
581   redispatch_to '/other/url';
582
583 The redispatch_to subroutine is designed for use inside dispatch subroutines.
584
585 It creates and returns a special dispatcher that always matches, and instead
586 of continuing dispatch re-delegates it to the start of the dispatch process,
587 but with the path of the request altered to the supplied URL.
588
589 Thus if you receive a POST to '/some/url' and return a redipstch to
590 '/other/url', the dispatch behaviour will be exactly as if the same POST
591 request had been made to '/other/url' instead.
592
593 =head2 subdispatch
594
595   subdispatch sub (/user/*/) {
596     my $u = $self->user($_[1]);
597     [
598       sub (GET) { $u },
599       sub (DELETE) { $u->delete },
600     ]
601   }
602
603 The subdispatch subroutine is designed for use in dispatcher construction.
604
605 It creates a dispatcher which, if it matches, treats its return value not
606 as a final value but an arrayref of dispatch specifications such as could
607 be passed to the dispatch subroutine itself. These are turned into a dispatcher
608 which is then invoked. Any changes the match makes to the request are in
609 scope for this inner dispatcher only - so if the initial match is a
610 destructive one like .html the full path will be restored if the
611 subdispatch fails.
612
613 =head1 CHANGES BETWEEN RELEASES
614
615 =head2 Changes since Antiquated Perl
616
617 =over 4
618
619 =item * filter_response renamed to response_filter
620
621 This is a pure rename; a global search and replace should fix it.
622
623 =item * dispatch [] changed to dispatch {}
624
625 Simply changing
626
627   dispatch [ sub(...) { ... }, ... ];
628
629 to
630
631   dispatch { sub(...) { ... }, ... };
632
633 should work fine.
634
635 =back
636
637 =head1 COMMUNITY AND SUPPORT
638
639 =head2 IRC channel
640
641 irc.perl.org #web-simple
642
643 =head2 No mailing list yet
644
645 Because mst's non-work email is a bombsite so he'd never read it anyway.
646
647 =head2 Git repository
648
649 Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
650
651   git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
652
653 =head1 AUTHOR
654
655 Matt S. Trout <mst@shadowcat.co.uk>
656
657 =head1 CONTRIBUTORS
658
659 None required yet. Maybe this module is perfect (hahahahaha ...).
660
661 =head1 COPYRIGHT
662
663 Copyright (c) 2009 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
664 as listed above.
665
666 =head1 LICENSE
667
668 This library is free software and may be distributed under the same terms
669 as perl itself.
670
671 =cut
672
673 1;