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}::self"} = \${"${app_package}::self"};
49 require Web::Simple::Application;
50 unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
52 (my $name = $app_package) =~ s/::/\//g;
53 $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
58 Web::Simple - A quick and easy way to build simple web applications
62 This is really quite new. If you're reading this on CPAN, it means the stuff
63 that's here we're probably happy with. But only probably. So we may have to
64 change stuff. And if you're reading this from git, come check with irc.perl.org
65 #web-simple that we're actually sure we're going to keep anything that's
66 different from the CPAN version.
68 If we do find we have to change stuff we'll add to the
69 L<CHANGES BETWEEN RELEASES> section explaining how to switch your code across
70 to the new version, and we'll do our best to make it as painless as possible
71 because we've got Web::Simple applications too. But we can't promise not to
72 change things at all. Not yet. Sorry.
78 use Web::Simple 'HelloWorld';
85 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
88 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
93 HelloWorld->run_if_script;
95 If you save this file into your cgi-bin as hello-world.cgi and then visit
97 http://my.server.name/cgi-bin/hello-world.cgi/
99 you'll get the "Hello world!" string output to your browser. For more complex
100 examples and non-CGI deployment, see below. To get help with Web::Simple,
101 please connect to the irc.perl.org IRC network and join #web-simple.
105 Web::Simple was originally written to form part of my Antiquated Perl talk for
106 Italian Perl Workshop 2009, but in writing the bloggery example I realised
107 that having a bare minimum system for writing web applications that doesn't
108 drive me insane was rather nice and decided to spend my attempt at nanowrimo
109 for 2009 improving and documenting it to the point where others could use it.
111 The philosophy of Web::Simple is to keep to an absolute bare minimum, for
112 everything. It is not designed to be used for large scale applications;
113 the L<Catalyst> web framework already works very nicely for that and is
114 a far more mature, well supported piece of software.
116 However, if you have an application that only does a couple of things, and
117 want to not have to think about complexities of deployment, then Web::Simple
118 might be just the thing for you.
120 The Antiquated Perl talk can be found at L<http://www.shadowcat.co.uk/archive/conference-video/>.
124 The only public interface the Web::Simple module itself provides is an
127 use Web::Simple 'NameOfApplication';
129 This imports 'strict' and 'warnings FATAL => "all"' into your code as well,
130 so you can skip the usual
135 provided you 'use Web::Simple' at the top of the file. Note that we turn
136 on *fatal* warnings so if you have any warnings at any point from the file
137 that you did 'use Web::Simple' in, then your application will die. This is,
138 so far, considered a feature.
140 Calling the import also makes NameOfApplication isa Web::Simple::Application
141 - i.e. does the equivalent of
144 package NameOfApplication;
145 use base qw(Web::Simple::Application);
148 It also exports the following subroutines:
155 dispatch { sub (...) { ... }, ... };
157 response_filter { ... };
159 redispatch_to '/somewhere';
161 subdispatch sub (...) { ... }
163 and creates a $self global variable in your application package, so you can
164 use $self in dispatch subs without violating strict (Web::Simple::Application
165 arranges for dispatch subroutines to have the correct $self in scope when
170 $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
172 so that perl will not attempt to load the application again even if
174 require NameOfApplication;
176 is encountered in other code.
178 =head1 DISPATCH STRATEGY
183 # matches: GET /user/1.htm?show_details=1
185 sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
186 shift; my ($user_id, $show_details) = @_;
189 # matches: POST /user?username=frew
190 # POST /user?username=mst&first_name=matt&last_name=trout
191 sub (POST + /user + ?username=&*) {
192 shift; my ($username, $misc_params) = @_;
195 # matches: DELETE /user/1/friend/2
196 sub (DELETE + /user/*/friend/*) {
197 shift; my ($user_id, $friend_id) = @_;
200 # matches: PUT /user/1?first_name=Matt&last_name=Trout
201 sub (PUT + /user/* + ?first_name~&last_name~) {
202 shift; my ($user_id, $first_name, $last_name) = @_;
209 # matches: PUT /user/1/role/1
210 sub (PUT + /role/*) {
214 # matches: DELETE /user/1/role/1
215 sub (DELETE + /role/*) {
224 =head2 Description of the dispatcher object
226 Web::Simple::Dispatcher objects have three components:
230 =item * match - an optional test if this dispatcher matches the request
232 =item * call - a routine to call if this dispatcher matches (or has no match)
234 =item * next - the next dispatcher to call
238 When a dispatcher is invoked, it checks its match routine against the
239 request environment. The match routine may provide alterations to the
240 request as a result of matching, and/or arguments for the call routine.
242 If no match routine has been provided then Web::Simple treats this as
243 a success, and supplies the request environment to the call routine as
246 Given a successful match, the call routine is now invoked in list context
247 with any arguments given to the original dispatch, plus any arguments
248 provided by the match result.
250 If this routine returns (), Web::Simple treats this identically to a failure
253 If this routine returns a Web::Simple::Dispatcher, the environment changes
254 are merged into the environment and the new dispatcher's next pointer is
255 set to our next pointer.
257 If this routine returns anything else, that is treated as the end of dispatch
258 and the value is returned.
260 On a failed match, Web::Simple invokes the next dispatcher with the same
261 arguments and request environment passed to the current one. On a successful
262 match that returned a new dispatcher, Web::Simple invokes the new dispatcher
263 with the same arguments but the modified request environment.
265 =head2 How Web::Simple builds dispatcher objects for you
267 In the case of the Web::Simple L</dispatch> export the match is constructed
268 from the subroutine prototype - i.e.
270 sub (<match specification>) {
274 and the 'next' pointer is populated with the next element of the array,
275 expect for the last element, which is given a next that will throw a 500
276 error if none of your dispatchers match. If you want to provide something
277 else as a default, a routine with no match specification always matches, so -
280 [ 404, [ 'Content-type', 'text/plain' ], [ 'Error: Not Found' ] ]
283 will produce a 404 result instead of a 500 by default. You can also override
284 the L<Web::Simple::Application/_build_final_dispatcher> method in your app.
286 Note that the code in the subroutine is executed as a -method- on your
287 application object, so if your match specification provides arguments you
288 should unpack them like so:
290 sub (<match specification>) {
291 my ($self, @args) = @_;
295 =head2 Web::Simple match specifications
297 =head3 Method matches
301 A match specification beginning with a capital letter matches HTTP requests
302 with that request method.
308 A match specification beginning with a / is a path match. In the simplest
309 case it matches a specific path. To match a path with a wildcard part, you
313 $self->handle_user($_[1])
315 This will match /user/<anything> where <anything> does not include a literal
316 / character. The matched part becomes part of the match arguments. You can
317 also match more than one part:
320 my ($self, $user_1, $user_2) = @_;
322 sub (/domain/*/user/*) {
323 my ($self, $domain, $user) = @_;
325 and so on. To match an arbitrary number of parts, use -
329 This will result in an element per /-separated part so matched. Note that
332 sub (/page/**/edit) {
334 to match an arbitrary number of parts up to but not including some final
341 will match /foo/ on the beginning of the path -and- strip it, much like
342 .html strips the extension. This is designed to be used to construct
343 nested dispatch structures, but can also prove useful for having e.g. an
344 optional language specification at the start of a path.
346 Note that the '...' is a "maybe something here, maybe not" so the above
347 specification will match like this:
350 /foo/ # match and strip path to '/'
351 /foo/bar/baz # match and strip path to '/bar/baz'
353 =head3 Extension matches
357 will match and strip .html from the path (assuming the subroutine itself
358 returns something, of course). This is normally used for rendering - e.g.
361 response_filter { $self->render_html($_[1]) }
368 will match any extension and supplies the stripped extension as a match
371 =head3 Query and body parameter matches
373 Query and body parameters can be match via
375 sub (?<param spec>) { # match URI query
376 sub (%<param spec>) { # match body params
378 The body is only matched if the content type is
379 application/x-www-form-urlencoded (note this means that Web::Simple does
380 not yet handle uploads; this will be addressed in a later release).
382 The param spec is elements of one of the following forms -
384 param~ # optional parameter
385 param= # required parameter
386 @param~ # optional multiple parameter
387 @param= # required multiple parameter
388 :param~ # optional parameter in hashref
389 :param= # required parameter in hashref
390 :@param~ # optional multiple in hashref
391 :@param= # required multiple in hashref
392 * # include all other parameters in hashref
393 @* # include all other parameters as multiple in hashref
395 separated by the & character. The arguments added to the request are
396 one per non-:/* parameter (scalar for normal, arrayref for multiple),
397 plus if any :/* specs exist a hashref containing those values.
399 So, to match a page parameter with an optional order_by parameter one
402 sub (?page=&order_by~) {
403 my ($self, $page, $order_by) = @_;
404 return unless $page =~ /^\d+$/;
407 $_[1]->search_rs({}, $p);
411 to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
413 Note that if a parameter is specified as single and multiple values are found,
414 the last one will be used.
416 To get all parameters as a hashref of arrayrefs, write:
419 my ($self, $params) = @_;
422 To get two parameters as a hashref, write:
424 sub(?:user~&:domain~) {
425 my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
427 You can also mix these, so:
429 sub (?foo=&@bar~&:coffee=&@*) {
430 my ($self, $foo, $bar, $params);
432 where $bar is an arrayref (possibly an empty one), and $params contains
433 arrayref values for all parameters -not- mentioned and a scalar value for
434 the 'coffee' parameter.
436 =head3 Combining matches
438 Matches may be combined with the + character - e.g.
440 sub (GET + /user/*) {
442 to create an AND match. They may also be combined withe the | character - e.g.
446 to create an OR match. Matches can be nested with () - e.g.
448 sub ((GET|POST) + /user/*) {
450 and negated with ! - e.g.
452 sub (!/user/foo + /user/*) {
454 ! binds to the immediate rightmost match specification, so if you want
455 to negate a combination you will need to use
457 sub ( !(POST|PUT|DELETE) ) {
459 and | binds tighter than +, so
461 sub ((GET|POST) + /user/*) {
465 sub (GET|POST + /user/*) {
469 sub ((GET + .html) | (POST + .html)) {
473 sub (GET + .html | POST + .html) {
475 are not - the latter is equivalent to
477 sub (GET + (.html|POST) + .html) {
479 which will never match.
483 Note that for legibility you are permitted to use whitespace -
485 sub (GET + /user/*) {
487 but it will be ignored. This is because the perl parser strips whitespace
488 from subroutine prototypes, so this is equivalent to
492 =head1 EXPORTED SUBROUTINES
494 =head2 default_config
498 another_key => 'bar',
503 $self->config->{one_key} # 'foo'
505 This creates the default configuration for the application, by creating a
507 sub _default_config {
508 return (one_key => 'foo', another_key => 'bar');
511 in the application namespace when executed. Note that this means that
512 you should only run default_config once - calling it a second time will
513 cause an exception to be thrown.
519 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
522 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
526 The dispatch subroutine calls NameOfApplication->_setup_dispatcher with
527 the return value of the block passed to it, which then creates your Web::Simple
528 application's dispatcher from these subs. The prototype of each subroutine
529 is expected to be a Web::Simple dispatch specification (see
530 L</DISPATCH SPECIFICATIONS> below for more details), and the body of the
531 subroutine is the code to execute if the specification matches.
533 Each dispatcher is given the dispatcher constructed from the next subroutine
534 returned as its next dispatcher, except for the final subroutine, which
535 is given the return value of NameOfApplication->_build_final_dispatcher
536 as its next dispatcher (by default this returns a 500 error response).
538 See L</DISPATCH STRATEGY> below for details on how the Web::Simple dispatch
539 system uses the return values of these subroutines to determine how to
540 continue, alter or abort dispatch.
542 Note that _setup_dispatcher creates a
545 return <root dispatcher object here>;
548 method in your class so as with default_config, calling dispatch a second time
549 will result in an exception.
551 =head2 response_filter
554 # Hide errors from the user because we hates them, preciousss
555 if (ref($_[1]) eq 'ARRAY' && $_[1]->[0] == 500) {
556 $_[1] = [ 200, @{$_[1]}[1..$#{$_[1]}] ];
561 The response_filter subroutine is designed for use inside dispatch subroutines.
563 It creates and returns a special dispatcher that always matches, and calls
564 the block passed to it as a filter on the result of running the rest of the
565 current dispatch chain.
567 Thus the filter above runs further dispatch as normal, but if the result of
568 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
569 response without altering the headers or body.
573 redispatch_to '/other/url';
575 The redispatch_to subroutine is designed for use inside dispatch subroutines.
577 It creates and returns a special dispatcher that always matches, and instead
578 of continuing dispatch re-delegates it to the start of the dispatch process,
579 but with the path of the request altered to the supplied URL.
581 Thus if you receive a POST to '/some/url' and return a redipstch to
582 '/other/url', the dispatch behaviour will be exactly as if the same POST
583 request had been made to '/other/url' instead.
587 subdispatch sub (/user/*/) {
588 my $u = $self->user($_[1]);
591 sub (DELETE) { $u->delete },
595 The subdispatch subroutine is designed for use in dispatcher construction.
597 It creates a dispatcher which, if it matches, treats its return value not
598 as a final value but an arrayref of dispatch specifications such as could
599 be passed to the dispatch subroutine itself. These are turned into a dispatcher
600 which is then invoked. Any changes the match makes to the request are in
601 scope for this inner dispatcher only - so if the initial match is a
602 destructive one like .html the full path will be restored if the
605 =head1 CHANGES BETWEEN RELEASES
607 =head2 Changes since Antiquated Perl
611 =item * filter_response renamed to response_filter
613 This is a pure rename; a global search and replace should fix it.
615 =item * dispatch [] changed to dispatch {}
619 dispatch [ sub(...) { ... }, ... ];
623 dispatch { sub(...) { ... }, ... };
629 =head1 COMMUNITY AND SUPPORT
633 irc.perl.org #web-simple
635 =head2 No mailing list yet
637 Because mst's non-work email is a bombsite so he'd never read it anyway.
639 =head2 Git repository
641 Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
643 git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
647 Matt S. Trout <mst@shadowcat.co.uk>
651 None required yet. Maybe this module is perfect (hahahahaha ...).
655 Copyright (c) 2009 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
660 This library is free software and may be distributed under the same terms