5 use warnings::illegalproto ();
7 use Web::Dispatch::Wrapper ();
9 our $VERSION = '0.004';
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: $@";
18 warnings::illegalproto->unimport;
22 my ($class, $app_package) = @_;
25 *{"${app_package}::PSGI_ENV"} = sub () { -1 };
26 require Web::Simple::Application;
27 unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
29 (my $name = $app_package) =~ s/::/\//g;
30 $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
35 Web::Simple - A quick and easy way to build simple web applications
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.
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.
55 use Web::Simple 'HelloWorld';
60 sub dispatch_request {
62 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
65 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
70 HelloWorld->run_if_script;
72 If you save this file into your cgi-bin as C<hello-world.cgi> and then visit:
74 http://my.server.name/cgi-bin/hello-world.cgi/
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 Web::Simple,
78 please connect to the irc.perl.org IRC network and join #web-simple.
82 The philosophy of 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.
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 Web::Simple
89 might be just the thing for you.
91 The only public interface the Web::Simple module itself provides is an
94 use Web::Simple 'NameOfApplication';
96 This imports 'strict' and 'warnings FATAL => "all"' into your code as well,
97 so you can skip the usual:
102 provided you 'use Web::Simple' at the top of the file. Note that we turn
103 on *fatal* warnings so if you have any warnings at any point from the file
104 that you did 'use Web::Simple' in, then your application will die. This is,
105 so far, considered a feature.
107 Calling the import also makes NameOfApplication isa Web::Simple::Application
108 and sets your app class up as a L<Moo> class- i.e. does the equivalent of
111 package NameOfApplication;
113 extends 'Web::Simple::Application';
116 It also exports the following subroutines for use in dispatchers:
118 response_filter { ... };
120 redispatch_to '/somewhere';
124 $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
126 so that perl will not attempt to load the application again even if
128 require NameOfApplication;
130 is encountered in other code.
132 =head1 DISPATCH STRATEGY
136 sub dispatch_request {
137 # matches: GET /user/1.htm?show_details=1
139 sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
140 my ($self, $user_id, $show_details) = @_;
143 # matches: POST /user?username=frew
144 # POST /user?username=mst&first_name=matt&last_name=trout
145 sub (POST + /user + ?username=&*) {
146 my ($self, $username, $misc_params) = @_;
149 # matches: DELETE /user/1/friend/2
150 sub (DELETE + /user/*/friend/*) {
151 my ($self, $user_id, $friend_id) = @_;
154 # matches: PUT /user/1?first_name=Matt&last_name=Trout
155 sub (PUT + /user/* + ?first_name~&last_name~) {
156 my ($self, $user_id, $first_name, $last_name) = @_;
161 # matches: PUT /user/1/role/1
162 sub (PUT + /role/*) {
166 # matches: DELETE /user/1/role/1
167 sub (DELETE + /role/*) {
174 =head2 The dispatch cycle
176 At the beginning of a request, your app's dispatch_request method is called
177 with the PSGI $env as an argument. You can handle the request entirely in
178 here and return a PSGI response arrayref if you want:
180 sub dispatch_request {
181 my ($self, $env) = @_;
182 [ 404, [ 'Content-type' => 'text/plain' ], [ 'Amnesia == fail' ] ]
185 However, generally, instead of that, you return a set of dispatch subs:
187 sub dispatch_request {
189 sub (/) { redispatch_to '/index.html' },
190 sub (/user/*) { $self->show_user($_[1]) },
194 If you return a subroutine with a prototype, the prototype is treated
195 as a match specification - and if the test is passed, the body of the
196 sub is called as a method any matched arguments (see below for more details).
198 You can also return a plain subroutine which will be called with just $env
199 - remember that in this case if you need $self you -must- close over it.
201 If you return a normal object, Web::Simple will simply return it upwards on
202 the assumption that a response_filter somewhere will convert it to something
203 useful - this allows:
205 sub dispatch_request {
207 sub (.html) { response_filter { $self->render_zoom($_[0]) } },
208 sub (/user/*) { $self->users->get($_[1]) },
211 to render a user object to HTML, for example.
213 However, two types of object are treated specially - a Plack::App object
214 will have its ->to_app method called and be used as a dispatcher:
216 sub dispatch_request {
218 sub (/static/...) { Plack::App::File->new(...) },
222 A Plack::Middleware object will be used as a filter for the rest of the
223 dispatch being returned into:
225 ## responds to /admin/track_usage AND /admin/delete_accounts
227 sub dispatch_request {
230 Plack::Middleware::Session->new(%opts);
232 sub (/admin/track_usage) {
233 ## something that needs a session
235 sub (/admin/delete_accounts) {
236 ## something else that needs a session
240 Note that this is for the dispatch being -returned- to, so if you want to
241 provide it inline you need to do:
243 ## ALSO responds to /admin/track_usage AND /admin/delete_accounts
245 sub dispatch_request {
249 Plack::Middleware::Session->new(%opts);
252 ## something that needs a session
254 sub (/delete_accounts) {
255 ## something else that needs a session
260 And that's it - but remember that all this happens recursively - it's
261 dispatchers all the way down.
263 =head2 Web::Simple match specifications
265 =head3 Method matches
269 A match specification beginning with a capital letter matches HTTP requests
270 with that request method.
276 A match specification beginning with a / is a path match. In the simplest
277 case it matches a specific path. To match a path with a wildcard part, you
281 $self->handle_user($_[1])
283 This will match /user/<anything> where <anything> does not include a literal
284 / character. The matched part becomes part of the match arguments. You can
285 also match more than one part:
288 my ($self, $user_1, $user_2) = @_;
290 sub (/domain/*/user/*) {
291 my ($self, $domain, $user) = @_;
293 and so on. To match an arbitrary number of parts, use -
297 This will result in an element per /-separated part so matched. Note that
300 sub (/page/**/edit) {
302 to match an arbitrary number of parts up to but not including some final
309 will match /foo/ on the beginning of the path -and- strip it, much like
310 .html strips the extension. This is designed to be used to construct
311 nested dispatch structures, but can also prove useful for having e.g. an
312 optional language specification at the start of a path.
314 Note that the '...' is a "maybe something here, maybe not" so the above
315 specification will match like this:
318 /foo/ # match and strip path to '/'
319 /foo/bar/baz # match and strip path to '/bar/baz'
321 =head3 Extension matches
325 will match and strip .html from the path (assuming the subroutine itself
326 returns something, of course). This is normally used for rendering - e.g.
329 response_filter { $self->render_html($_[1]) }
336 will match any extension and supplies the stripped extension as a match
339 =head3 Query and body parameter matches
341 Query and body parameters can be match via
343 sub (?<param spec>) { # match URI query
344 sub (%<param spec>) { # match body params
346 The body is only matched if the content type is
347 application/x-www-form-urlencoded (note this means that Web::Simple does
348 not yet handle uploads; this will be addressed in a later release).
350 The param spec is elements of one of the following forms -
352 param~ # optional parameter
353 param= # required parameter
354 @param~ # optional multiple parameter
355 @param= # required multiple parameter
356 :param~ # optional parameter in hashref
357 :param= # required parameter in hashref
358 :@param~ # optional multiple in hashref
359 :@param= # required multiple in hashref
360 * # include all other parameters in hashref
361 @* # include all other parameters as multiple in hashref
363 separated by the & character. The arguments added to the request are
364 one per non-:/* parameter (scalar for normal, arrayref for multiple),
365 plus if any :/* specs exist a hashref containing those values.
367 So, to match a page parameter with an optional order_by parameter one
370 sub (?page=&order_by~) {
371 my ($self, $page, $order_by) = @_;
372 return unless $page =~ /^\d+$/;
375 $_[1]->search_rs({}, $p);
379 to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
381 Note that if a parameter is specified as single and multiple values are found,
382 the last one will be used.
384 To get all parameters as a hashref of arrayrefs, write:
387 my ($self, $params) = @_;
390 To get two parameters as a hashref, write:
392 sub(?:user~&:domain~) {
393 my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
395 You can also mix these, so:
397 sub (?foo=&@bar~&:coffee=&@*) {
398 my ($self, $foo, $bar, $params);
400 where $bar is an arrayref (possibly an empty one), and $params contains
401 arrayref values for all parameters -not- mentioned and a scalar value for
402 the 'coffee' parameter.
404 =head3 Combining matches
406 Matches may be combined with the + character - e.g.
408 sub (GET + /user/*) {
410 to create an AND match. They may also be combined withe the | character - e.g.
414 to create an OR match. Matches can be nested with () - e.g.
416 sub ((GET|POST) + /user/*) {
418 and negated with ! - e.g.
420 sub (!/user/foo + /user/*) {
422 ! binds to the immediate rightmost match specification, so if you want
423 to negate a combination you will need to use
425 sub ( !(POST|PUT|DELETE) ) {
427 and | binds tighter than +, so
429 sub ((GET|POST) + /user/*) {
433 sub (GET|POST + /user/*) {
437 sub ((GET + .html) | (POST + .html)) {
441 sub (GET + .html | POST + .html) {
443 are not - the latter is equivalent to
445 sub (GET + (.html|POST) + .html) {
447 which will never match.
451 Note that for legibility you are permitted to use whitespace -
453 sub (GET + /user/*) {
455 but it will be ignored. This is because the perl parser strips whitespace
456 from subroutine prototypes, so this is equivalent to
460 =head3 Accessing the PSGI env hash
462 In some cases you may wish to get the raw PSGI env hash - to do this,
463 you can either use a plain sub -
470 or use the PSGI_ENV constant exported to retrieve it:
472 sub (GET + /foo + ?some_param=) {
474 my $env = $_[PSGI_ENV];
477 but note that if you're trying to add a middleware, you should simply use
478 Web::Simple's direct support for doing so.
480 =head1 EXPORTED SUBROUTINES
482 =head2 response_filter
485 # Hide errors from the user because we hates them, preciousss
486 if (ref($_[0]) eq 'ARRAY' && $_[0]->[0] == 500) {
487 $_[0] = [ 200, @{$_[0]}[1..$#{$_[0]}] ];
492 The response_filter subroutine is designed for use inside dispatch subroutines.
494 It creates and returns a special dispatcher that always matches, and calls
495 the block passed to it as a filter on the result of running the rest of the
496 current dispatch chain.
498 Thus the filter above runs further dispatch as normal, but if the result of
499 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
500 response without altering the headers or body.
504 redispatch_to '/other/url';
506 The redispatch_to subroutine is designed for use inside dispatch subroutines.
508 It creates and returns a special dispatcher that always matches, and instead
509 of continuing dispatch re-delegates it to the start of the dispatch process,
510 but with the path of the request altered to the supplied URL.
512 Thus if you receive a POST to '/some/url' and return a redispatch to
513 '/other/url', the dispatch behaviour will be exactly as if the same POST
514 request had been made to '/other/url' instead.
516 =head1 CHANGES BETWEEN RELEASES
518 =head2 Changes between 0.004 and 0.005
522 =item * dispatch {} replaced by declaring a dispatch_request method
524 dispatch {} has gone away - instead, you write:
526 sub dispatch_request {
528 sub (GET /foo/) { ... },
532 Note that this method is still -returning- the dispatch code - just like
535 Also note that you need the 'my $self = shift' since the magic $self
538 =item * the magic $self variable went away.
540 Just add 'my $self = shift;' while writing your 'sub dispatch_request {'
541 like a normal perl method.
543 =item * subdispatch deleted - all dispatchers can now subdispatch
545 In earlier releases you needed to write:
547 subdispatch sub (/foo/...) {
550 sub (GET /bar/) { ... },
555 As of 0.005, you can instead write simply:
560 sub (GET /bar/) { ... },
565 =head2 Changes since Antiquated Perl
569 =item * filter_response renamed to response_filter
571 This is a pure rename; a global search and replace should fix it.
573 =item * dispatch [] changed to dispatch {}
577 dispatch [ sub(...) { ... }, ... ];
581 dispatch { sub(...) { ... }, ... };
587 =head1 DEVELOPMENT HISTORY
589 Web::Simple was originally written to form part of my Antiquated Perl talk for
590 Italian Perl Workshop 2009, but in writing the bloggery example I realised
591 that having a bare minimum system for writing web applications that doesn't
592 drive me insane was rather nice and decided to spend my attempt at nanowrimo
593 for 2009 improving and documenting it to the point where others could use it.
595 The Antiquated Perl talk can be found at L<http://www.shadowcat.co.uk/archive/conference-video/>.
597 =head1 COMMUNITY AND SUPPORT
601 irc.perl.org #web-simple
603 =head2 No mailing list yet
605 Because mst's non-work email is a bombsite so he'd never read it anyway.
607 =head2 Git repository
609 Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
611 git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
615 Matt S. Trout <mst@shadowcat.co.uk>
619 None required yet. Maybe this module is perfect (hahahahaha ...).
623 Copyright (c) 2009 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
628 This library is free software and may be distributed under the same terms