4 use warnings FATAL => 'all';
7 our $VERSION = '0.002';
9 sub setup_all_strictures {
11 warnings->import(FATAL => 'all');
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
24 setup_dispatch_strictures();
25 my ($class, $app_package) = @_;
26 $class->_export_into($app_package);
30 my ($class, $app_package) = @_;
33 *{"${app_package}::dispatch"} = sub (&) {
34 $app_package->_setup_dispatcher([ $_[0]->() ]);
36 *{"${app_package}::response_filter"} = sub (&) {
37 $app_package->_construct_response_filter($_[0]);
39 *{"${app_package}::redispatch_to"} = sub {
40 $app_package->_construct_redispatch($_[0]);
42 *{"${app_package}::subdispatch"} = sub ($) {
43 $app_package->_construct_subdispatch($_[0]);
45 *{"${app_package}::default_config"} = sub {
46 $app_package->_setup_default_config(@_);
48 *{"${app_package}::ENV"} = sub () { -1 };
49 *{"${app_package}::self"} = \${"${app_package}::self"};
50 require Web::Simple::Application;
51 unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
53 (my $name = $app_package) =~ s/::/\//g;
54 $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
59 Web::Simple - A quick and easy way to build simple web applications
63 This is really quite new. If you're reading this on CPAN, it means the stuff
64 that's here we're probably happy with. But only probably. So we may have to
65 change stuff. And if you're reading this from git, come check with irc.perl.org
66 #web-simple that we're actually sure we're going to keep anything that's
67 different from the CPAN version.
69 If we do find we have to change stuff we'll add to the
70 L<CHANGES BETWEEN RELEASES> section explaining how to switch your code across
71 to the new version, and we'll do our best to make it as painless as possible
72 because we've got Web::Simple applications too. But we can't promise not to
73 change things at all. Not yet. Sorry.
79 use Web::Simple 'HelloWorld';
86 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
89 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
94 HelloWorld->run_if_script;
96 If you save this file into your cgi-bin as hello-world.cgi and then visit
98 http://my.server.name/cgi-bin/hello-world.cgi/
100 you'll get the "Hello world!" string output to your browser. For more complex
101 examples and non-CGI deployment, see below. To get help with Web::Simple,
102 please connect to the irc.perl.org IRC network and join #web-simple.
106 Web::Simple was originally written to form part of my Antiquated Perl talk for
107 Italian Perl Workshop 2009, but in writing the bloggery example I realised
108 that having a bare minimum system for writing web applications that doesn't
109 drive me insane was rather nice and decided to spend my attempt at nanowrimo
110 for 2009 improving and documenting it to the point where others could use it.
112 The philosophy of Web::Simple is to keep to an absolute bare minimum, for
113 everything. It is not designed to be used for large scale applications;
114 the L<Catalyst> web framework already works very nicely for that and is
115 a far more mature, well supported piece of software.
117 However, if you have an application that only does a couple of things, and
118 want to not have to think about complexities of deployment, then Web::Simple
119 might be just the thing for you.
121 The Antiquated Perl talk can be found at L<http://www.shadowcat.co.uk/archive/conference-video/>.
125 The only public interface the Web::Simple module itself provides is an
128 use Web::Simple 'NameOfApplication';
130 This imports 'strict' and 'warnings FATAL => "all"' into your code as well,
131 so you can skip the usual
136 provided you 'use Web::Simple' at the top of the file. Note that we turn
137 on *fatal* warnings so if you have any warnings at any point from the file
138 that you did 'use Web::Simple' in, then your application will die. This is,
139 so far, considered a feature.
141 Calling the import also makes NameOfApplication isa Web::Simple::Application
142 - i.e. does the equivalent of
145 package NameOfApplication;
146 use base qw(Web::Simple::Application);
149 It also exports the following subroutines:
156 dispatch { sub (...) { ... }, ... };
158 response_filter { ... };
160 redispatch_to '/somewhere';
162 subdispatch sub (...) { ... }
164 and creates a $self global variable in your application package, so you can
165 use $self in dispatch subs without violating strict (Web::Simple::Application
166 arranges for dispatch subroutines to have the correct $self in scope when
171 $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
173 so that perl will not attempt to load the application again even if
175 require NameOfApplication;
177 is encountered in other code.
179 =head1 DISPATCH STRATEGY
184 # matches: GET /user/1.htm?show_details=1
186 sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
187 shift; my ($user_id, $show_details) = @_;
190 # matches: POST /user?username=frew
191 # POST /user?username=mst&first_name=matt&last_name=trout
192 sub (POST + /user + ?username=&*) {
193 shift; my ($username, $misc_params) = @_;
196 # matches: DELETE /user/1/friend/2
197 sub (DELETE + /user/*/friend/*) {
198 shift; my ($user_id, $friend_id) = @_;
201 # matches: PUT /user/1?first_name=Matt&last_name=Trout
202 sub (PUT + /user/* + ?first_name~&last_name~) {
203 shift; my ($user_id, $first_name, $last_name) = @_;
210 # matches: PUT /user/1/role/1
211 sub (PUT + /role/*) {
215 # matches: DELETE /user/1/role/1
216 sub (DELETE + /role/*) {
225 =head2 Description of the dispatcher object
227 Web::Simple::Dispatcher objects have three components:
231 =item * match - an optional test if this dispatcher matches the request
233 =item * call - a routine to call if this dispatcher matches (or has no match)
235 =item * next - the next dispatcher to call
239 When a dispatcher is invoked, it checks its match routine against the
240 request environment. The match routine may provide alterations to the
241 request as a result of matching, and/or arguments for the call routine.
243 If no match routine has been provided then Web::Simple treats this as
244 a success, and supplies the request environment to the call routine as
247 Given a successful match, the call routine is now invoked in list context
248 with any arguments given to the original dispatch, plus any arguments
249 provided by the match result.
251 If this routine returns (), Web::Simple treats this identically to a failure
254 If this routine returns a Web::Simple::Dispatcher, the environment changes
255 are merged into the environment and the new dispatcher's next pointer is
256 set to our next pointer.
258 If this routine returns anything else, that is treated as the end of dispatch
259 and the value is returned.
261 On a failed match, Web::Simple invokes the next dispatcher with the same
262 arguments and request environment passed to the current one. On a successful
263 match that returned a new dispatcher, Web::Simple invokes the new dispatcher
264 with the same arguments but the modified request environment.
266 =head2 How Web::Simple builds dispatcher objects for you
268 In the case of the Web::Simple L</dispatch> export the match is constructed
269 from the subroutine prototype - i.e.
271 sub (<match specification>) {
275 and the 'next' pointer is populated with the next element of the array,
276 expect for the last element, which is given a next that will throw a 500
277 error if none of your dispatchers match. If you want to provide something
278 else as a default, a routine with no match specification always matches, so -
281 [ 404, [ 'Content-type', 'text/plain' ], [ 'Error: Not Found' ] ]
284 will produce a 404 result instead of a 500 by default. You can also override
285 the L<Web::Simple::Application/_build_final_dispatcher> method in your app.
287 Note that the code in the subroutine is executed as a -method- on your
288 application object, so if your match specification provides arguments you
289 should unpack them like so:
291 sub (<match specification>) {
292 my ($self, @args) = @_;
296 =head2 Web::Simple match specifications
298 =head3 Method matches
302 A match specification beginning with a capital letter matches HTTP requests
303 with that request method.
309 A match specification beginning with a / is a path match. In the simplest
310 case it matches a specific path. To match a path with a wildcard part, you
314 $self->handle_user($_[1])
316 This will match /user/<anything> where <anything> does not include a literal
317 / character. The matched part becomes part of the match arguments. You can
318 also match more than one part:
321 my ($self, $user_1, $user_2) = @_;
323 sub (/domain/*/user/*) {
324 my ($self, $domain, $user) = @_;
326 and so on. To match an arbitrary number of parts, use -
330 This will result in an element per /-separated part so matched. Note that
333 sub (/page/**/edit) {
335 to match an arbitrary number of parts up to but not including some final
342 will match /foo/ on the beginning of the path -and- strip it, much like
343 .html strips the extension. This is designed to be used to construct
344 nested dispatch structures, but can also prove useful for having e.g. an
345 optional language specification at the start of a path.
347 Note that the '...' is a "maybe something here, maybe not" so the above
348 specification will match like this:
351 /foo/ # match and strip path to '/'
352 /foo/bar/baz # match and strip path to '/bar/baz'
354 =head3 Extension matches
358 will match and strip .html from the path (assuming the subroutine itself
359 returns something, of course). This is normally used for rendering - e.g.
362 response_filter { $self->render_html($_[1]) }
369 will match any extension and supplies the stripped extension as a match
372 =head3 Query and body parameter matches
374 Query and body parameters can be match via
376 sub (?<param spec>) { # match URI query
377 sub (%<param spec>) { # match body params
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).
383 The param spec is elements of one of the following forms -
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
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.
400 So, to match a page parameter with an optional order_by parameter one
403 sub (?page=&order_by~) {
404 my ($self, $page, $order_by) = @_;
405 return unless $page =~ /^\d+$/;
408 $_[1]->search_rs({}, $p);
412 to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
414 Note that if a parameter is specified as single and multiple values are found,
415 the last one will be used.
417 To get all parameters as a hashref of arrayrefs, write:
420 my ($self, $params) = @_;
423 To get two parameters as a hashref, write:
425 sub(?:user~&:domain~) {
426 my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
428 You can also mix these, so:
430 sub (?foo=&@bar~&:coffee=&@*) {
431 my ($self, $foo, $bar, $params);
433 where $bar is an arrayref (possibly an empty one), and $params contains
434 arrayref values for all parameters -not- mentioned and a scalar value for
435 the 'coffee' parameter.
437 =head3 Combining matches
439 Matches may be combined with the + character - e.g.
441 sub (GET + /user/*) {
443 to create an AND match. They may also be combined withe the | character - e.g.
447 to create an OR match. Matches can be nested with () - e.g.
449 sub ((GET|POST) + /user/*) {
451 and negated with ! - e.g.
453 sub (!/user/foo + /user/*) {
455 ! binds to the immediate rightmost match specification, so if you want
456 to negate a combination you will need to use
458 sub ( !(POST|PUT|DELETE) ) {
460 and | binds tighter than +, so
462 sub ((GET|POST) + /user/*) {
466 sub (GET|POST + /user/*) {
470 sub ((GET + .html) | (POST + .html)) {
474 sub (GET + .html | POST + .html) {
476 are not - the latter is equivalent to
478 sub (GET + (.html|POST) + .html) {
480 which will never match.
484 Note that for legibility you are permitted to use whitespace -
486 sub (GET + /user/*) {
488 but it will be ignored. This is because the perl parser strips whitespace
489 from subroutine prototypes, so this is equivalent to
493 =head3 Accessing the PSGI env hash
495 To gain the benefit of using some middleware, specifically
496 Plack::Middleware::Session access to the ENV hash is needed. This is provided
497 in arguments to the dispatched handler. You can access this hash with the
498 exported +ENV constant.
500 sub (GET + /foo + ?some_param=) {
501 my($self, $some_param, $env) = @_[0, 1, +ENV];
503 =head1 EXPORTED SUBROUTINES
505 =head2 default_config
509 another_key => 'bar',
514 $self->config->{one_key} # 'foo'
516 This creates the default configuration for the application, by creating a
518 sub _default_config {
519 return (one_key => 'foo', another_key => 'bar');
522 in the application namespace when executed. Note that this means that
523 you should only run default_config once - calling it a second time will
524 cause an exception to be thrown.
530 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
533 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
537 The dispatch subroutine calls NameOfApplication->_setup_dispatcher with
538 the return value of the block passed to it, which then creates your Web::Simple
539 application's dispatcher from these subs. The prototype of each subroutine
540 is expected to be a Web::Simple dispatch specification (see
541 L</DISPATCH SPECIFICATIONS> below for more details), and the body of the
542 subroutine is the code to execute if the specification matches.
544 Each dispatcher is given the dispatcher constructed from the next subroutine
545 returned as its next dispatcher, except for the final subroutine, which
546 is given the return value of NameOfApplication->_build_final_dispatcher
547 as its next dispatcher (by default this returns a 500 error response).
549 See L</DISPATCH STRATEGY> below for details on how the Web::Simple dispatch
550 system uses the return values of these subroutines to determine how to
551 continue, alter or abort dispatch.
553 Note that _setup_dispatcher creates a
556 return <root dispatcher object here>;
559 method in your class so as with default_config, calling dispatch a second time
560 will result in an exception.
562 =head2 response_filter
565 # Hide errors from the user because we hates them, preciousss
566 if (ref($_[1]) eq 'ARRAY' && $_[1]->[0] == 500) {
567 $_[1] = [ 200, @{$_[1]}[1..$#{$_[1]}] ];
572 The response_filter subroutine is designed for use inside dispatch subroutines.
574 It creates and returns a special dispatcher that always matches, and calls
575 the block passed to it as a filter on the result of running the rest of the
576 current dispatch chain.
578 Thus the filter above runs further dispatch as normal, but if the result of
579 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
580 response without altering the headers or body.
584 redispatch_to '/other/url';
586 The redispatch_to subroutine is designed for use inside dispatch subroutines.
588 It creates and returns a special dispatcher that always matches, and instead
589 of continuing dispatch re-delegates it to the start of the dispatch process,
590 but with the path of the request altered to the supplied URL.
592 Thus if you receive a POST to '/some/url' and return a redipstch to
593 '/other/url', the dispatch behaviour will be exactly as if the same POST
594 request had been made to '/other/url' instead.
598 subdispatch sub (/user/*/) {
599 my $u = $self->user($_[1]);
602 sub (DELETE) { $u->delete },
606 The subdispatch subroutine is designed for use in dispatcher construction.
608 It creates a dispatcher which, if it matches, treats its return value not
609 as a final value but an arrayref of dispatch specifications such as could
610 be passed to the dispatch subroutine itself. These are turned into a dispatcher
611 which is then invoked. Any changes the match makes to the request are in
612 scope for this inner dispatcher only - so if the initial match is a
613 destructive one like .html the full path will be restored if the
616 =head1 CHANGES BETWEEN RELEASES
618 =head2 Changes since Antiquated Perl
622 =item * filter_response renamed to response_filter
624 This is a pure rename; a global search and replace should fix it.
626 =item * dispatch [] changed to dispatch {}
630 dispatch [ sub(...) { ... }, ... ];
634 dispatch { sub(...) { ... }, ... };
640 =head1 COMMUNITY AND SUPPORT
644 irc.perl.org #web-simple
646 =head2 No mailing list yet
648 Because mst's non-work email is a bombsite so he'd never read it anyway.
650 =head2 Git repository
652 Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
654 git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
658 Matt S. Trout <mst@shadowcat.co.uk>
662 None required yet. Maybe this module is perfect (hahahahaha ...).
666 Copyright (c) 2009 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
671 This library is free software and may be distributed under the same terms