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