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