simplified synopsis and created deployment pod
[catagits/Web-Simple.git] / lib / Web / Simple.pm
1 package Web::Simple;
2
3 use strictures 1;
4 use 5.008;
5 use warnings::illegalproto ();
6 use Moo ();
7 use Web::Dispatch::Wrapper ();
8
9 our $VERSION = '0.009';
10
11 sub import {
12   my ($class, $app_package) = @_;
13   $app_package ||= caller;
14   $class->_export_into($app_package);
15   eval "package $app_package; use Web::Dispatch::Wrapper; use Moo; 1"
16     or die "Failed to setup app package: $@";
17   strictures->import;
18   warnings::illegalproto->unimport;
19 }
20
21 sub _export_into {
22   my ($class, $app_package) = @_;
23   {
24     no strict 'refs';
25     *{"${app_package}::PSGI_ENV"} = sub () { -1 };
26     require Web::Simple::Application;
27     unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
28   }
29   (my $name = $app_package) =~ s/::/\//g;
30   $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
31 }
32
33 =head1 NAME
34
35 Web::Simple - A quick and easy way to build simple web applications
36
37
38 =head1 SYNOPSIS
39
40   #!/usr/bin/env perl
41
42   package HelloWorld;
43   use Web::Simple
44
45   sub dispatch_request {
46     sub (GET) {
47       [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
48     },
49     sub () {
50       [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
51     }
52   }
53
54   HelloWorld->run_if_script;
55
56 If you save this file into your cgi-bin as C<hello-world.cgi> and then visit:
57
58   http://my.server.name/cgi-bin/hello-world.cgi/
59
60 you'll get the "Hello world!" string output to your browser. At the same time
61 this file will also act as a class module, so you can save it as HelloWorld.pm
62 and use it as-is in test scripts or other deployment mechanisms.
63
64 For more complex examples and non-CGI deployment, see
65 L<Web::Simple::Deployment>. To get help with L<Web::Simple>, please connect to
66 the irc.perl.org IRC network and join #web-simple.
67
68 =head1 DESCRIPTION
69
70 The philosophy of L<Web::Simple> is to keep to an absolute bare minimum for
71 everything. It is not designed to be used for large scale applications;
72 the L<Catalyst> web framework already works very nicely for that and is
73 a far more mature, well supported piece of software.
74
75 However, if you have an application that only does a couple of things, and
76 want to not have to think about complexities of deployment, then L<Web::Simple>
77 might be just the thing for you.
78
79 The only public interface the L<Web::Simple> module itself provides is an
80 C<import> based one:
81
82   use Web::Simple 'NameOfApplication';
83
84 This sets up your package (in this case "NameOfApplication" is your package)
85 so that it inherits from L<Web::Simple::Application> and imports L<strictures>,
86 as well as installs a C<PSGI_ENV> constant for convenience, as well as some 
87 other subroutines.
88
89 Importing L<strictures> will automatically make your code use the C<strict> and
90 C<warnings> pragma, so you can skip the usual:
91
92   use strict;
93   use warnings FATAL => 'aa';
94
95 provided you 'use Web::Simple' at the top of the file. Note that we turn
96 on *fatal* warnings so if you have any warnings at any point from the file
97 that you did 'use Web::Simple' in, then your application will die. This is,
98 so far, considered a feature.
99
100 When we inherit from L<Web::Simple::Application> we also use L<Moo>, which is
101 the the equivalent of:
102
103   {
104     package NameOfApplication;
105     use Moo;
106     extends 'Web::Simple::Application';
107   }
108
109 So you can use L<Moo> features in your application, such as creating attributes
110 using the C<has> subroutine, etc.  Please see the documentation for L<Moo> for
111 more information.
112
113 It also exports the following subroutines for use in dispatchers:
114
115   response_filter { ... };
116
117   redispatch_to '/somewhere';
118
119 Finally, import sets
120
121   $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
122
123 so that perl will not attempt to load the application again even if
124
125   require NameOfApplication;
126
127 is encountered in other code.
128
129 =head1 DISPATCH STRATEGY
130
131 L<Web::Simple> despite being straightforward to use, has a powerful system
132 for matching all sorts of incoming URLs to one or more subroutines.  These
133 subroutines can be simple actions to take for a given URL, or something
134 more complicated, including entire L<Plack> applications, L<Plack::Middleware>
135 and nested subdispatchers.
136
137 =head2 Examples
138
139  sub dispatch_request {
140    # matches: GET /user/1.htm?show_details=1
141    #          GET /user/1.htm
142    sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
143      my ($self, $user_id, $show_details) = @_;
144      ...
145    },
146    # matches: POST /user?username=frew
147    #          POST /user?username=mst&first_name=matt&last_name=trout
148    sub (POST + /user + ?username=&*) {
149       my ($self, $username, $misc_params) = @_;
150      ...
151    },
152    # matches: DELETE /user/1/friend/2
153    sub (DELETE + /user/*/friend/*) {
154      my ($self, $user_id, $friend_id) = @_;
155      ...
156    },
157    # matches: PUT /user/1?first_name=Matt&last_name=Trout
158    sub (PUT + /user/* + ?first_name~&last_name~) {
159      my ($self, $user_id, $first_name, $last_name) = @_;
160      ...
161    },
162    sub (/user/*/...) {
163      my $user_id = $_[1];
164      # matches: PUT /user/1/role/1
165      sub (PUT + /role/*) {
166        my $role_id = $_[1];
167        ...
168      },
169      # matches: DELETE /user/1/role/1
170      sub (DELETE + /role/*) {
171        my $role_id = $_[1];
172        ...
173      },
174    },
175  }
176
177 =head2 The dispatch cycle
178
179 At the beginning of a request, your app's dispatch_request method is called
180 with the PSGI $env as an argument. You can handle the request entirely in
181 here and return a PSGI response arrayref if you want:
182
183   sub dispatch_request {
184     my ($self, $env) = @_;
185     [ 404, [ 'Content-type' => 'text/plain' ], [ 'Amnesia == fail' ] ]
186   }
187
188 However, generally, instead of that, you return a set of dispatch subs:
189
190   sub dispatch_request {
191     my $self = shift;
192     sub (/) { redispatch_to '/index.html' },
193     sub (/user/*) { $self->show_user($_[1]) },
194     ...
195   }
196
197 If you return a subroutine with a prototype, the prototype is treated
198 as a match specification - and if the test is passed, the body of the
199 sub is called as a method any matched arguments (see below for more details).
200
201 You can also return a plain subroutine which will be called with just $env
202 - remember that in this case if you need $self you -must- close over it.
203
204 If you return a normal object, L<Web::Simple> will simply return it upwards on
205 the assumption that a response_filter (or some arbitrary L<Plack::Middleware>)
206 somewhere will convert it to something useful.  This allows:
207
208   sub dispatch_request {
209     my $self = shift;
210     sub (.html) { response_filter { $self->render_zoom($_[0]) } },
211     sub (/user/*) { $self->users->get($_[1]) },
212   }
213
214 to render a user object to HTML, if there is an incoming URL such as:
215
216   http://myweb.org/user/111.html
217
218 This works because as we descend down the dispachers, we first match
219 C<sub (.html)>, which adds a C<response_filter> (basically a specialized routine
220 that follows the L<Plack::Middleware> specification), and then later we also
221 match C<sub (/user/*)> which gets a user and returns that as the response.
222 This user object 'bubbles up' through all the wrapping middleware until it hits
223 the C<response_filter> we defined, after which the return is converted to a
224 true html response.
225
226 However, two types of object are treated specially - a Plack::App object
227 will have its C<->to_app> method called and be used as a dispatcher:
228
229   sub dispatch_request {
230     my $self = shift;
231     sub (/static/...) { Plack::App::File->new(...) },
232     ...
233   }
234
235 A Plack::Middleware object will be used as a filter for the rest of the
236 dispatch being returned into:
237
238   ## responds to /admin/track_usage AND /admin/delete_accounts
239
240   sub dispatch_request {
241     my $self = shift;
242     sub (/admin/**) {
243       Plack::Middleware::Session->new(%opts);
244     },
245     sub (/admin/track_usage) {
246       ## something that needs a session
247     },
248     sub (/admin/delete_accounts) {
249       ## something else that needs a session
250     },
251   }
252
253 Note that this is for the dispatch being -returned- to, so if you want to
254 provide it inline you need to do:
255
256   ## ALSO responds to /admin/track_usage AND /admin/delete_accounts
257
258   sub dispatch_request {
259     my $self = shift;
260     sub (/admin/...) {
261       sub {
262         Plack::Middleware::Session->new(%opts);
263       },
264       sub (/track_usage) {
265         ## something that needs a session
266       },
267       sub (/delete_accounts) {
268         ## something else that needs a session
269       },
270     }
271   }
272
273 And that's it - but remember that all this happens recursively - it's
274 dispatchers all the way down.  A URL incoming pattern will run all matching
275 dispatchers and then hit all added filters or L<Plack::Middleware>.
276
277 =head2 Web::Simple match specifications
278
279 =head3 Method matches
280
281   sub (GET) {
282
283 A match specification beginning with a capital letter matches HTTP requests
284 with that request method.
285
286 =head3 Path matches
287
288   sub (/login) {
289
290 A match specification beginning with a / is a path match. In the simplest
291 case it matches a specific path. To match a path with a wildcard part, you
292 can do:
293
294   sub (/user/*) {
295     $self->handle_user($_[1])
296
297 This will match /user/<anything> where <anything> does not include a literal
298 / character. The matched part becomes part of the match arguments. You can
299 also match more than one part:
300
301   sub (/user/*/*) {
302     my ($self, $user_1, $user_2) = @_;
303
304   sub (/domain/*/user/*) {
305     my ($self, $domain, $user) = @_;
306
307 and so on. To match an arbitrary number of parts, use -
308
309   sub (/page/**) {
310
311 This will result in an element per /-separated part so matched. Note that
312 you can do
313
314   sub (/page/**/edit) {
315
316 to match an arbitrary number of parts up to but not including some final
317 part.
318
319 Finally,
320
321   sub (/foo/...) {
322
323 Will match /foo/ on the beginning of the path -and- strip it. This is designed
324 to be used to construct nested dispatch structures, but can also prove useful
325 for having e.g. an optional language specification at the start of a path.
326
327 Note that the '...' is a "maybe something here, maybe not" so the above
328 specification will match like this:
329
330   /foo         # no match
331   /foo/        # match and strip path to '/'
332   /foo/bar/baz # match and strip path to '/bar/baz'
333
334 Note: Since Web::Simple handles a concept of file extensions, * and **
335 matchers will not by default match things after a final dot, and this
336 can be modified by using *.* and **.* in the final position, i.e.:
337
338   /one/*       matches /one/two.three    and captures "two"
339   /one/*.*     matches /one/two.three    and captures "two.three"
340   /**          matches /one/two.three    and captures "one/two"
341   /**.*        matches /one/two.three    and captures "one/two.three"
342
343 =head3 Extension matches
344
345   sub (.html) {
346
347 will match .html from the path (assuming the subroutine itself returns
348 something, of course). This is normally used for rendering - e.g.
349
350   sub (.html) {
351     response_filter { $self->render_html($_[1]) }
352   }
353
354 Additionally,
355
356   sub (.*) {
357
358 will match any extension and supplies the extension as a match argument.
359
360 =head3 Query and body parameter matches
361
362 Query and body parameters can be match via
363
364   sub (?<param spec>) { # match URI query
365   sub (%<param spec>) { # match body params
366
367 The body spec will match if the request content is either
368 application/x-www-form-urlencoded or multipart/form-data - the latter
369 of which is required for uploads, which are now handled experimentally
370 - see below.
371
372 The param spec is elements of one of the following forms -
373
374   param~        # optional parameter
375   param=        # required parameter
376   @param~       # optional multiple parameter
377   @param=       # required multiple parameter
378   :param~       # optional parameter in hashref
379   :param=       # required parameter in hashref
380   :@param~      # optional multiple in hashref
381   :@param=      # required multiple in hashref
382   *             # include all other parameters in hashref
383   @*            # include all other parameters as multiple in hashref
384
385 separated by the & character. The arguments added to the request are
386 one per non-:/* parameter (scalar for normal, arrayref for multiple),
387 plus if any :/* specs exist a hashref containing those values.
388
389 Please note that if you specify a multiple type parameter match, you are
390 ensured of getting an arrayref for the value, EVEN if the current incoming
391 request has only one value.  However if a parameter is specified as single
392 and multiple values are found, the last one will be used.
393
394 For example to match a page parameter with an optional order_by parameter one
395 would write:
396
397   sub (?page=&order_by~) {
398     my ($self, $page, $order_by) = @_;
399     return unless $page =~ /^\d+$/;
400     $page ||= 'id';
401     response_filter {
402       $_[1]->search_rs({}, $p);
403     }
404   }
405
406 to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
407
408 Another Example: To get all parameters as a hashref of arrayrefs, write:
409
410   sub(?@*) {
411     my ($self, $params) = @_;
412     ...
413
414 To get two parameters as a hashref, write:
415
416   sub(?:user~&:domain~) {
417     my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
418
419 You can also mix these, so:
420
421   sub (?foo=&@bar~&:coffee=&@*) {
422      my ($self, $foo, $bar, $params);
423
424 where $bar is an arrayref (possibly an empty one), and $params contains
425 arrayref values for all parameters -not- mentioned and a scalar value for
426 the 'coffee' parameter.
427
428 Note, in the case where you combine arrayref, single parameter and named
429 hashref style, the arrayref and single parameters will appear in C<@_> in the
430 order you defined them in the protoype, but all hashrefs will merge into a 
431 single C<$params>, as in the example above.
432
433 =head3 Upload matches (EXPERIMENTAL)
434
435 Note: This feature is experimental. This means that it may not remain
436 100% in its current form. If we change it, notes on updating your code
437 will be added to the L</CHANGES BETWEEN RELEASES> section below.
438
439   sub (*foo=) { # param specifier can be anything valid for query or body
440
441 The upload match system functions exactly like a query/body match, except
442 that the values returned (if any) are C<Web::Dispatch::Upload> objects.
443
444 Note that this match type will succeed in two circumstances where you might
445 not expect it to - first, when the field exists but is not an upload field
446 and second, when the field exists but the form is not an upload form (i.e.
447 content type "application/x-www-form-urlencoded" rather than
448 "multipart/form-data"). In either of these cases, what you'll get back is
449 a C<Web::Dispatch::NotAnUpload> object, which will C<die> with an error
450 pointing out the problem if you try and use it. To be sure you have a real
451 upload object, call
452
453   $upload->is_upload # returns 1 on a valid upload, 0 on a non-upload field
454
455 and to get the reason why such an object is not an upload, call
456
457   $upload->reason # returns a reason or '' on a valid upload.
458
459 Other than these two methods, the upload object provides the same interface
460 as L<Plack::Request::Upload> with the addition of a stringify to the temporary
461 filename to make copying it somewhere else easier to handle.
462
463 =head3 Combining matches
464
465 Matches may be combined with the + character - e.g.
466
467   sub (GET + /user/*) {
468
469 to create an AND match. They may also be combined withe the | character - e.g.
470
471   sub (GET|POST) {
472
473 to create an OR match. Matches can be nested with () - e.g.
474
475   sub ((GET|POST) + /user/*) {
476
477 and negated with ! - e.g.
478
479   sub (!/user/foo + /user/*) {
480
481 ! binds to the immediate rightmost match specification, so if you want
482 to negate a combination you will need to use
483
484   sub ( !(POST|PUT|DELETE) ) {
485
486 and | binds tighter than +, so
487
488   sub ((GET|POST) + /user/*) {
489
490 and
491
492   sub (GET|POST + /user/*) {
493
494 are equivalent, but
495
496   sub ((GET + /admin/...) | (POST + /admin/...)) {
497
498 and
499
500   sub (GET + /admin/... | POST + /admin/...) {
501
502 are not - the latter is equivalent to
503
504   sub (GET + (/admin/...|POST) + /admin/...) {
505
506 which will never match!
507
508 =head3 Whitespace
509
510 Note that for legibility you are permitted to use whitespace -
511
512   sub (GET + /user/*) {
513
514 but it will be ignored. This is because the perl parser strips whitespace
515 from subroutine prototypes, so this is equivalent to
516
517   sub (GET+/user/*) {
518
519 =head3 Accessing the PSGI env hash
520
521 In some cases you may wish to get the raw PSGI env hash - to do this,
522 you can either use a plain sub -
523
524   sub {
525     my ($env) = @_;
526     ...
527   }
528
529 or use the PSGI_ENV constant exported to retrieve it:
530
531   sub (GET + /foo + ?some_param=) {
532     my $param = $_[1];
533     my $env = $_[PSGI_ENV];
534   }
535
536 but note that if you're trying to add a middleware, you should simply use
537 Web::Simple's direct support for doing so.
538
539 =head1 EXPORTED SUBROUTINES
540
541 =head2 response_filter
542
543   response_filter {
544     # Hide errors from the user because we hates them, preciousss
545     if (ref($_[0]) eq 'ARRAY' && $_[0]->[0] == 500) {
546       $_[0] = [ 200, @{$_[0]}[1..$#{$_[0]}] ];
547     }
548     return $_[0];
549   };
550
551 The response_filter subroutine is designed for use inside dispatch subroutines.
552
553 It creates and returns a special dispatcher that always matches, and calls
554 the block passed to it as a filter on the result of running the rest of the
555 current dispatch chain.
556
557 Thus the filter above runs further dispatch as normal, but if the result of
558 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
559 response without altering the headers or body.
560
561 =head2 redispatch_to
562
563   redispatch_to '/other/url';
564
565 The redispatch_to subroutine is designed for use inside dispatch subroutines.
566
567 It creates and returns a special dispatcher that always matches, and instead
568 of continuing dispatch re-delegates it to the start of the dispatch process,
569 but with the path of the request altered to the supplied URL.
570
571 Thus if you receive a POST to '/some/url' and return a redispatch to
572 '/other/url', the dispatch behaviour will be exactly as if the same POST
573 request had been made to '/other/url' instead.
574
575 Note, this is not the same as returning an HTTP 3xx redirect as a response;
576 rather it is a much more efficient internal process.  
577
578 =head1 CHANGES BETWEEN RELEASES
579
580 =head2 Changes between 0.004 and 0.005
581
582 =over 4
583
584 =item * dispatch {} replaced by declaring a dispatch_request method
585
586 dispatch {} has gone away - instead, you write:
587
588   sub dispatch_request {
589     my $self = shift;
590     sub (GET /foo/) { ... },
591     ...
592   }
593
594 Note that this method is still -returning- the dispatch code - just like
595 dispatch did.
596
597 Also note that you need the 'my $self = shift' since the magic $self
598 variable went away.
599
600 =item * the magic $self variable went away.
601
602 Just add 'my $self = shift;' while writing your 'sub dispatch_request {'
603 like a normal perl method.
604
605 =item * subdispatch deleted - all dispatchers can now subdispatch
606
607 In earlier releases you needed to write:
608
609   subdispatch sub (/foo/...) {
610     ...
611     [
612       sub (GET /bar/) { ... },
613       ...
614     ]
615   }
616
617 As of 0.005, you can instead write simply:
618
619   sub (/foo/...) {
620     ...
621     (
622       sub (GET /bar/) { ... },
623       ...
624     )
625   }
626
627 =back
628
629 =head2 Changes since Antiquated Perl
630
631 =over 4
632
633 =item * filter_response renamed to response_filter
634
635 This is a pure rename; a global search and replace should fix it.
636
637 =item * dispatch [] changed to dispatch {}
638
639 Simply changing
640
641   dispatch [ sub(...) { ... }, ... ];
642
643 to
644
645   dispatch { sub(...) { ... }, ... };
646
647 should work fine.
648
649 =back
650
651 =head1 DEVELOPMENT HISTORY
652
653 Web::Simple was originally written to form part of my Antiquated Perl talk for
654 Italian Perl Workshop 2009, but in writing the bloggery example I realised
655 that having a bare minimum system for writing web applications that doesn't
656 drive me insane was rather nice and decided to spend my attempt at nanowrimo
657 for 2009 improving and documenting it to the point where others could use it.
658
659 The Antiquated Perl talk can be found at L<http://www.shadowcat.co.uk/archive/conference-video/> and the slides are reproduced in this distribution under
660 L<Web::Simple::AntiquatedPerl>.
661
662 =head1 COMMUNITY AND SUPPORT
663
664 =head2 IRC channel
665
666 irc.perl.org #web-simple
667
668 =head2 No mailing list yet
669
670 Because mst's non-work email is a bombsite so he'd never read it anyway.
671
672 =head2 Git repository
673
674 Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
675
676   git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
677
678 =head1 AUTHOR
679
680 Matt S. Trout (mst) <mst@shadowcat.co.uk>
681
682 =head1 CONTRIBUTORS
683
684 Devin Austin (dhoss) <dhoss@cpan.org>
685
686 Arthur Axel 'fREW' Schmidt <frioux@gmail.com>
687
688 gregor herrmann (gregoa) <gregoa@debian.org>
689
690 John Napiorkowski (jnap) <jjn1056@yahoo.com>
691
692 Josh McMichael <jmcmicha@linus222.gsc.wustl.edu>
693
694 Justin Hunter <justin.d.hunter@gmail.com>
695
696 Kjetil Kjernsmo <kjetil@kjernsmo.net>
697
698 markie <markie@nulletch64.dreamhost.com>
699
700 Christian Walde (Mithaldu) <walde.christian@googlemail.com>
701
702 nperez <nperez@cpan.org>
703
704 Robin Edwards <robin.ge@gmail.com>
705
706 =head1 COPYRIGHT
707
708 Copyright (c) 2010 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
709 as listed above.
710
711 =head1 LICENSE
712
713 This library is free software and may be distributed under the same terms
714 as perl itself.
715
716 =cut
717
718 1;