4 use warnings FATAL => 'all';
7 our $VERSION = '0.004';
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||caller);
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}::default_config"} = sub {
43 $app_package->_setup_default_config(@_);
45 *{"${app_package}::PSGI_ENV"} = sub () { -1 };
46 *{"${app_package}::self"} = \${"${app_package}::self"};
47 require Web::Simple::Application;
48 unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
50 (my $name = $app_package) =~ s/::/\//g;
51 $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
56 Web::Simple - A quick and easy way to build simple web applications
60 This is really quite new. If you're reading this on CPAN, it means the stuff
61 that's here we're probably happy with. But only probably. So we may have to
62 change stuff. And if you're reading this from git, come check with irc.perl.org
63 #web-simple that we're actually sure we're going to keep anything that's
64 different from the CPAN version.
66 If we do find we have to change stuff we'll add to the
67 L<CHANGES BETWEEN RELEASES> section explaining how to switch your code across
68 to the new version, and we'll do our best to make it as painless as possible
69 because we've got Web::Simple applications too. But we can't promise not to
70 change things at all. Not yet. Sorry.
76 use Web::Simple 'HelloWorld';
83 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
86 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
91 HelloWorld->run_if_script;
93 If you save this file into your cgi-bin as hello-world.cgi and then visit
95 http://my.server.name/cgi-bin/hello-world.cgi/
97 you'll get the "Hello world!" string output to your browser. For more complex
98 examples and non-CGI deployment, see below. To get help with Web::Simple,
99 please connect to the irc.perl.org IRC network and join #web-simple.
103 Web::Simple was originally written to form part of my Antiquated Perl talk for
104 Italian Perl Workshop 2009, but in writing the bloggery example I realised
105 that having a bare minimum system for writing web applications that doesn't
106 drive me insane was rather nice and decided to spend my attempt at nanowrimo
107 for 2009 improving and documenting it to the point where others could use it.
109 The philosophy of Web::Simple is to keep to an absolute bare minimum, for
110 everything. It is not designed to be used for large scale applications;
111 the L<Catalyst> web framework already works very nicely for that and is
112 a far more mature, well supported piece of software.
114 However, if you have an application that only does a couple of things, and
115 want to not have to think about complexities of deployment, then Web::Simple
116 might be just the thing for you.
118 The Antiquated Perl talk can be found at L<http://www.shadowcat.co.uk/archive/conference-video/>.
122 The only public interface the Web::Simple module itself provides is an
125 use Web::Simple 'NameOfApplication';
127 This imports 'strict' and 'warnings FATAL => "all"' into your code as well,
128 so you can skip the usual
133 provided you 'use Web::Simple' at the top of the file. Note that we turn
134 on *fatal* warnings so if you have any warnings at any point from the file
135 that you did 'use Web::Simple' in, then your application will die. This is,
136 so far, considered a feature.
138 Calling the import also makes NameOfApplication isa Web::Simple::Application
139 - i.e. does the equivalent of
142 package NameOfApplication;
143 use base qw(Web::Simple::Application);
146 It also exports the following subroutines:
153 dispatch { sub (...) { ... }, ... };
155 response_filter { ... };
157 redispatch_to '/somewhere';
159 subdispatch sub (...) { ... }
161 and creates a $self global variable in your application package, so you can
162 use $self in dispatch subs without violating strict (Web::Simple::Application
163 arranges for dispatch subroutines to have the correct $self in scope when
168 $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
170 so that perl will not attempt to load the application again even if
172 require NameOfApplication;
174 is encountered in other code.
176 =head1 DISPATCH STRATEGY
181 # matches: GET /user/1.htm?show_details=1
183 sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
184 my ($self, $user_id, $show_details) = @_;
187 # matches: POST /user?username=frew
188 # POST /user?username=mst&first_name=matt&last_name=trout
189 sub (POST + /user + ?username=&*) {
190 my ($self, $username, $misc_params) = @_;
193 # matches: DELETE /user/1/friend/2
194 sub (DELETE + /user/*/friend/*) {
195 my ($self, $user_id, $friend_id) = @_;
198 # matches: PUT /user/1?first_name=Matt&last_name=Trout
199 sub (PUT + /user/* + ?first_name~&last_name~) {
200 my ($self, $user_id, $first_name, $last_name) = @_;
207 # matches: PUT /user/1/role/1
208 sub (PUT + /role/*) {
212 # matches: DELETE /user/1/role/1
213 sub (DELETE + /role/*) {
222 =head2 Description of the dispatcher object
224 Web::Simple::Dispatcher objects have three components:
228 =item * match - an optional test if this dispatcher matches the request
230 =item * call - a routine to call if this dispatcher matches (or has no match)
232 =item * next - the next dispatcher to call
236 When a dispatcher is invoked, it checks its match routine against the
237 request environment. The match routine may provide alterations to the
238 request as a result of matching, and/or arguments for the call routine.
240 If no match routine has been provided then Web::Simple treats this as
241 a success, and supplies the request environment to the call routine as
244 Given a successful match, the call routine is now invoked in list context
245 with any arguments given to the original dispatch, plus any arguments
246 provided by the match result.
248 If this routine returns (), Web::Simple treats this identically to a failure
251 If this routine returns a Web::Simple::Dispatcher, the environment changes
252 are merged into the environment and the new dispatcher's next pointer is
253 set to our next pointer.
255 If this routine returns anything else, that is treated as the end of dispatch
256 and the value is returned.
258 On a failed match, Web::Simple invokes the next dispatcher with the same
259 arguments and request environment passed to the current one. On a successful
260 match that returned a new dispatcher, Web::Simple invokes the new dispatcher
261 with the same arguments but the modified request environment.
263 =head2 How Web::Simple builds dispatcher objects for you
265 In the case of the Web::Simple L</dispatch> export the match is constructed
266 from the subroutine prototype - i.e.
268 sub (<match specification>) {
272 and the 'next' pointer is populated with the next element of the array,
273 expect for the last element, which is given a next that will throw a 500
274 error if none of your dispatchers match. If you want to provide something
275 else as a default, a routine with no match specification always matches, so -
278 [ 404, [ 'Content-type', 'text/plain' ], [ 'Error: Not Found' ] ]
281 will produce a 404 result instead of a 500 by default. You can also override
282 the L<Web::Simple::Application/_build_final_dispatcher> method in your app.
284 Note that the code in the subroutine is executed as a -method- on your
285 application object, so if your match specification provides arguments you
286 should unpack them like so:
288 sub (<match specification>) {
289 my ($self, @args) = @_;
293 =head2 Web::Simple match specifications
295 =head3 Method matches
299 A match specification beginning with a capital letter matches HTTP requests
300 with that request method.
306 A match specification beginning with a / is a path match. In the simplest
307 case it matches a specific path. To match a path with a wildcard part, you
311 $self->handle_user($_[1])
313 This will match /user/<anything> where <anything> does not include a literal
314 / character. The matched part becomes part of the match arguments. You can
315 also match more than one part:
318 my ($self, $user_1, $user_2) = @_;
320 sub (/domain/*/user/*) {
321 my ($self, $domain, $user) = @_;
323 and so on. To match an arbitrary number of parts, use -
327 This will result in an element per /-separated part so matched. Note that
330 sub (/page/**/edit) {
332 to match an arbitrary number of parts up to but not including some final
339 will match /foo/ on the beginning of the path -and- strip it, much like
340 .html strips the extension. This is designed to be used to construct
341 nested dispatch structures, but can also prove useful for having e.g. an
342 optional language specification at the start of a path.
344 Note that the '...' is a "maybe something here, maybe not" so the above
345 specification will match like this:
348 /foo/ # match and strip path to '/'
349 /foo/bar/baz # match and strip path to '/bar/baz'
351 =head3 Extension matches
355 will match and strip .html from the path (assuming the subroutine itself
356 returns something, of course). This is normally used for rendering - e.g.
359 response_filter { $self->render_html($_[1]) }
366 will match any extension and supplies the stripped extension as a match
369 =head3 Query and body parameter matches
371 Query and body parameters can be match via
373 sub (?<param spec>) { # match URI query
374 sub (%<param spec>) { # match body params
376 The body is only matched if the content type is
377 application/x-www-form-urlencoded (note this means that Web::Simple does
378 not yet handle uploads; this will be addressed in a later release).
380 The param spec is elements of one of the following forms -
382 param~ # optional parameter
383 param= # required parameter
384 @param~ # optional multiple parameter
385 @param= # required multiple parameter
386 :param~ # optional parameter in hashref
387 :param= # required parameter in hashref
388 :@param~ # optional multiple in hashref
389 :@param= # required multiple in hashref
390 * # include all other parameters in hashref
391 @* # include all other parameters as multiple in hashref
393 separated by the & character. The arguments added to the request are
394 one per non-:/* parameter (scalar for normal, arrayref for multiple),
395 plus if any :/* specs exist a hashref containing those values.
397 So, to match a page parameter with an optional order_by parameter one
400 sub (?page=&order_by~) {
401 my ($self, $page, $order_by) = @_;
402 return unless $page =~ /^\d+$/;
405 $_[1]->search_rs({}, $p);
409 to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
411 Note that if a parameter is specified as single and multiple values are found,
412 the last one will be used.
414 To get all parameters as a hashref of arrayrefs, write:
417 my ($self, $params) = @_;
420 To get two parameters as a hashref, write:
422 sub(?:user~&:domain~) {
423 my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
425 You can also mix these, so:
427 sub (?foo=&@bar~&:coffee=&@*) {
428 my ($self, $foo, $bar, $params);
430 where $bar is an arrayref (possibly an empty one), and $params contains
431 arrayref values for all parameters -not- mentioned and a scalar value for
432 the 'coffee' parameter.
434 =head3 Combining matches
436 Matches may be combined with the + character - e.g.
438 sub (GET + /user/*) {
440 to create an AND match. They may also be combined withe the | character - e.g.
444 to create an OR match. Matches can be nested with () - e.g.
446 sub ((GET|POST) + /user/*) {
448 and negated with ! - e.g.
450 sub (!/user/foo + /user/*) {
452 ! binds to the immediate rightmost match specification, so if you want
453 to negate a combination you will need to use
455 sub ( !(POST|PUT|DELETE) ) {
457 and | binds tighter than +, so
459 sub ((GET|POST) + /user/*) {
463 sub (GET|POST + /user/*) {
467 sub ((GET + .html) | (POST + .html)) {
471 sub (GET + .html | POST + .html) {
473 are not - the latter is equivalent to
475 sub (GET + (.html|POST) + .html) {
477 which will never match.
481 Note that for legibility you are permitted to use whitespace -
483 sub (GET + /user/*) {
485 but it will be ignored. This is because the perl parser strips whitespace
486 from subroutine prototypes, so this is equivalent to
490 =head3 Accessing the PSGI env hash
492 To gain the benefit of using some middleware, specifically
493 Plack::Middleware::Session access to the ENV hash is needed. This is provided
494 in arguments to the dispatched handler. You can access this hash with the
495 exported +PSGI_ENV constant.
497 sub (GET + /foo + ?some_param=) {
498 my($self, $some_param, $env) = @_[0, 1, +PSGI_ENV];
500 =head1 EXPORTED SUBROUTINES
502 =head2 default_config
506 another_key => 'bar',
511 $self->config->{one_key} # 'foo'
513 This creates the default configuration for the application, by creating a
515 sub _default_config {
516 return (one_key => 'foo', another_key => 'bar');
519 in the application namespace when executed. Note that this means that
520 you should only run default_config once - calling it a second time will
521 cause an exception to be thrown.
527 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
530 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
534 The dispatch subroutine calls NameOfApplication->_setup_dispatcher with
535 the return value of the block passed to it, which then creates your Web::Simple
536 application's dispatcher from these subs. The prototype of each subroutine
537 is expected to be a Web::Simple dispatch specification (see
538 L</DISPATCH SPECIFICATIONS> below for more details), and the body of the
539 subroutine is the code to execute if the specification matches.
541 Each dispatcher is given the dispatcher constructed from the next subroutine
542 returned as its next dispatcher, except for the final subroutine, which
543 is given the return value of NameOfApplication->_build_final_dispatcher
544 as its next dispatcher (by default this returns a 500 error response).
546 See L</DISPATCH STRATEGY> below for details on how the Web::Simple dispatch
547 system uses the return values of these subroutines to determine how to
548 continue, alter or abort dispatch.
550 Note that _setup_dispatcher creates a
553 return <root dispatcher object here>;
556 method in your class so as with default_config, calling dispatch a second time
557 will result in an exception.
559 =head2 response_filter
562 # Hide errors from the user because we hates them, preciousss
563 if (ref($_[1]) eq 'ARRAY' && $_[1]->[0] == 500) {
564 $_[1] = [ 200, @{$_[1]}[1..$#{$_[1]}] ];
569 The response_filter subroutine is designed for use inside dispatch subroutines.
571 It creates and returns a special dispatcher that always matches, and calls
572 the block passed to it as a filter on the result of running the rest of the
573 current dispatch chain.
575 Thus the filter above runs further dispatch as normal, but if the result of
576 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
577 response without altering the headers or body.
581 redispatch_to '/other/url';
583 The redispatch_to subroutine is designed for use inside dispatch subroutines.
585 It creates and returns a special dispatcher that always matches, and instead
586 of continuing dispatch re-delegates it to the start of the dispatch process,
587 but with the path of the request altered to the supplied URL.
589 Thus if you receive a POST to '/some/url' and return a redipstch to
590 '/other/url', the dispatch behaviour will be exactly as if the same POST
591 request had been made to '/other/url' instead.
595 subdispatch sub (/user/*/) {
596 my $u = $self->user($_[1]);
599 sub (DELETE) { $u->delete },
603 The subdispatch subroutine is designed for use in dispatcher construction.
605 It creates a dispatcher which, if it matches, treats its return value not
606 as a final value but an arrayref of dispatch specifications such as could
607 be passed to the dispatch subroutine itself. These are turned into a dispatcher
608 which is then invoked. Any changes the match makes to the request are in
609 scope for this inner dispatcher only - so if the initial match is a
610 destructive one like .html the full path will be restored if the
613 =head1 CHANGES BETWEEN RELEASES
615 =head2 Changes since Antiquated Perl
619 =item * filter_response renamed to response_filter
621 This is a pure rename; a global search and replace should fix it.
623 =item * dispatch [] changed to dispatch {}
627 dispatch [ sub(...) { ... }, ... ];
631 dispatch { sub(...) { ... }, ... };
637 =head1 COMMUNITY AND SUPPORT
641 irc.perl.org #web-simple
643 =head2 No mailing list yet
645 Because mst's non-work email is a bombsite so he'd never read it anyway.
647 =head2 Git repository
649 Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
651 git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
655 Matt S. Trout <mst@shadowcat.co.uk>
659 None required yet. Maybe this module is perfect (hahahahaha ...).
663 Copyright (c) 2009 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
668 This library is free software and may be distributed under the same terms