4 use warnings FATAL => 'all';
6 sub setup_all_strictures {
8 warnings->import(FATAL => 'all');
11 sub setup_dispatch_strictures {
12 setup_all_strictures();
13 warnings->unimport('syntax');
14 warnings->import(FATAL => qw(
15 ambiguous bareword digit parenthesis precedence printf
16 prototype qw reserved semicolon
21 setup_dispatch_strictures();
22 my ($class, $app_package) = @_;
23 $class->_export_into($app_package);
27 my ($class, $app_package) = @_;
30 *{"${app_package}::dispatch"} = sub {
31 $app_package->_setup_dispatcher(@_);
33 *{"${app_package}::filter_response"} = sub (&) {
34 $app_package->_construct_response_filter($_[0]);
36 *{"${app_package}::redispatch_to"} = sub {
37 $app_package->_construct_redispatch($_[0]);
39 *{"${app_package}::subdispatch"} = sub ($) {
40 $app_package->_construct_subdispatch($_[0]);
42 *{"${app_package}::default_config"} = sub {
43 $app_package->_setup_default_config(@_);
45 *{"${app_package}::self"} = \${"${app_package}::self"};
46 require Web::Simple::Application;
47 unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
49 (my $name = $app_package) =~ s/::/\//g;
50 $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
55 Web::Simple - A quick and easy way to build simple web applications
59 This is really quite new. If you're reading this from git, it means it's
60 really really new and we're still playing with things. If you're reading
61 this on CPAN, it means the stuff that's here we're probably happy with. But
62 only probably. So we may have to change stuff.
64 If we do find we have to change stuff we'll add a section explaining how to
65 switch your code across to the new version, and we'll do our best to make it
66 as painless as possible because we've got Web::Simple applications too. But
67 we can't promise not to change things at all. Not yet. Sorry.
73 use Web::Simple 'HelloWorld';
80 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
83 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
88 HelloWorld->run_if_script;
90 If you save this file into your cgi-bin as hello-world.cgi and then visit
92 http://my.server.name/cgi-bin/hello-world.cgi/
94 you'll get the "Hello world!" string output to your browser. For more complex
95 examples and non-CGI deployment, see below.
99 Web::Simple was originally written to form part of my Antiquated Perl talk for
100 Italian Perl Workshop 2009, but in writing the bloggery example I realised
101 that having a bare minimum system for writing web applications that doesn't
102 drive me insane was rather nice and decided to spend my attempt at nanowrimo
103 for 2009 improving and documenting it to the point where others could use it.
105 The philosophy of Web::Simple is to keep to an absolute bare minimum, for
106 everything. It is not designed to be used for large scale applications;
107 the L<Catalyst> web framework already works very nicely for that and is
108 a far more mature, well supported piece of software.
110 However, if you have an application that only does a couple of things, and
111 want to not have to think about complexities of deployment, then Web::Simple
112 might be just the thing for you.
114 The Antiquated Perl talk can be found at L<http://www.shadowcat.co.uk/archive/conference-video/>.
118 The only public interface the Web::Simple module itself provides is an
121 use Web::Simple 'NameOfApplication';
123 This imports 'strict' and 'warnings FATAL => "all"' into your code as well,
124 so you can skip the usual
129 provided you 'use Web::Simple' at the top of the file. Note that we turn
130 on *fatal* warnings so if you have any warnings at any point from the file
131 that you did 'use Web::Simple' in, then your application will die. This is,
132 so far, considered a feature.
134 Calling the import also makes NameOfApplication isa Web::Simple::Application
135 - i.e. does the equivalent of
138 package NameOfApplication;
139 use base qw(Web::Simple::Application);
142 It also exports the following subroutines:
149 dispatch [ sub (...) { ... }, ... ];
151 filter_response { ... };
153 redispatch_to '/somewhere';
155 subdispatch sub (...) { ... }
157 and creates a $self global variable in your application package, so you can
158 use $self in dispatch subs without violating strict (Web::Simple::Application
159 arranges for dispatch subroutines to have the correct $self in scope when
164 $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
166 so that perl will not attempt to load the application again even if
168 require NameOfApplication;
170 is encountered in other code.
172 =head1 EXPORTED SUBROUTINES
174 =head2 default_config
178 another_key => 'bar',
183 $self->config->{one_key} # 'foo'
185 This creates the default configuration for the application, by creating a
187 sub _default_config {
188 return (one_key => 'foo', another_key => 'bar');
191 in the application namespace when executed. Note that this means that
192 you should only run default_config once - calling it a second time will
193 cause an exception to be thrown.
199 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
202 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
206 The dispatch subroutine calls NameOfApplication->_setup_dispatcher with
207 the subroutines passed to it, which then creates your Web::Simple
208 application's dispatcher from these subs. The prototype of the subroutine
209 is expected to be a Web::Simple dispatch specification (see
210 L</DISPATCH SPECIFICATIONS> below for more details), and the body of the
211 subroutine is the code to execute if the specification matches. See
212 L</DISPATCH STRATEGY> below for details on how the Web::Simple dispatch
213 system uses the return values of these subroutines to determine how to
214 continue, alter or abort dispatch.
216 Note that _setup_dispatcher creates a
219 return <root dispatcher object here>;
222 method in your class so as with default_config, calling dispatch a second time
223 will result in an exception.
225 =head2 response_filter
228 # Hide errors from the user because we hates them, preciousss
229 if (ref($_[1]) eq 'ARRAY' && $_[1]->[0] == 500) {
230 $_[1] = [ 200, @{$_[1]}[1..$#{$_[1]}] ];
235 The response_filter subroutine is designed for use inside dispatch subroutines.
237 It creates and returns a special dispatcher that always matches, and calls
238 the block passed to it as a filter on the result of running the rest of the
239 current dispatch chain.
241 Thus the filter above runs further dispatch as normal, but if the result of
242 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
243 response without altering the headers or body.
247 redispatch_to '/other/url';
249 The redispatch_to subroutine is designed for use inside dispatch subroutines.
251 It creates and returns a special dispatcher that always matches, and instead
252 of continuing dispatch re-delegates it to the start of the dispatch process,
253 but with the path of the request altered to the supplied URL.
255 Thus if you receive a POST to '/some/url' and return a redipstch to
256 '/other/url', the dispatch behaviour will be exactly as if the same POST
257 request had been made to '/other/url' instead.
261 subdispatch sub (/user/*/) {
262 my $u = $self->user($_[1]);
265 sub (DELETE) { $u->delete },
269 The subdispatch subroutine is designed for use in dispatcher construction.
271 It creates a dispatcher which, if it matches, treats its return value not
272 as a final value but an arrayref of dispatch specifications such as could
273 be passed to the dispatch subroutine itself. These are turned into a dispatcher
274 which is then invoked. Any changes the match makes to the request are in
275 scope for this inner dispatcher only - so if the initial match is a
276 destructive one like .html the full path will be restored if the
279 =head1 DISPATCH STRATEGY
281 =head2 Description of the dispatcher object
283 Web::Simple::Dispatcher objects have three components:
287 =item * match - an optional test if this dispatcher matches the request
289 =item * call - a routine to call if this dispatcher matches (or has no match)
291 =item * next - the next dispatcher to call
295 When a dispatcher is invoked, it checks its match routine against the
296 request environment. The match routine may provide alterations to the
297 request as a result of matching, and/or arguments for the call routine.
299 If no match routine has been provided then Web::Simple treats this as
300 a success, and supplies the request environment to the call routine as
303 Given a successful match, the call routine is now invoked in list context
304 with any arguments given to the original dispatch, plus any arguments
305 provided by the match result.
307 If this routine returns (), Web::Simple treats this identically to a failure
310 If this routine returns a Web::Simple::Dispatcher, the environment changes
311 are merged into the environment and the new dispatcher's next pointer is
312 set to our next pointer.
314 If this routine returns anything else, that is treated as the end of dispatch
315 and the value is returned.
317 On a failed match, Web::Simple invokes the next dispatcher with the same
318 arguments and request environment passed to the current one. On a successful
319 match that returned a new dispatcher, Web::Simple invokes the new dispatcher
320 with the same arguments but the modified request environment.
322 =head2 How Web::Simple builds dispatcher objects for you
324 In the case of the Web::Simple L</dispatch> export the match is constructed
325 from the subroutine prototype - i.e.
327 sub (<match specification>) {
331 and the 'next' pointer is populated with the next element of the array,
332 expect for the last element, which is given a next that will throw a 500
333 error if none of your dispatchers match. If you want to provide something
334 else as a default, a routine with no match specification always matches, so -
337 [ 404, [ 'Content-type', 'text/plain' ], [ 'Error: Not Found' ] ]
340 will produce a 404 result instead of a 500 by default. You can also override
341 the L<Web::Simple::Application/_build_final_dispatcher> method in your app.
343 Note that the code in the subroutine is executed as a -method- on your
344 application object, so if your match specification provides arguments you
345 should unpack them like so:
347 sub (<match specification>) {
348 my ($self, @args) = @_;
352 =head2 Web::Simple match specifications
354 =head3 Method matches
358 A match specification beginning with a capital letter matches HTTP requests
359 with that request method.
365 A match specification beginning with a / is a path match. In the simplest
366 case it matches a specific path. To match a path with a wildcard part, you
370 $self->handle_user($_[1])
372 This will match /user/<anything> where <anything> does not include a literal
373 / character. The matched part becomes part of the match arguments. You can
374 also match more than one part:
377 my ($self, $user_1, $user_2) = @_;
379 sub (/domain/*/user/*) {
380 my ($self, $domain, $user) = @_;
382 and so on. To match an arbitrary number of parts, use -
386 This will result in an element per /-separated part so matched. Note that
389 sub (/page/**/edit) {
391 to match an arbitrary number of parts up to but not including some final
398 will match /foo/ on the beginning of the path -and- strip it, much like
399 .html strips the extension. This is designed to be used to construct
400 nested dispatch structures, but can also prove useful for having e.g. an
401 optional language specification at the start of a path.
403 Note that the '...' is a "maybe something here, maybe not" so the above
404 specification will match like this:
407 /foo/ # match and strip path to '/'
408 /foo/bar/baz # match and strip path to '/bar/baz'
410 =head3 Extension matches
414 will match and strip .html from the path (assuming the subroutine itself
415 returns something, of course). This is normally used for rendering - e.g.
418 filter_response { $self->render_html($_[1]) }
425 will match any extension and supplies the stripped extension as a match
428 =head3 Combining matches
430 Matches may be combined with the + character - e.g.
432 sub (GET + /user/*) {
434 to create an AND match. They may also be combined withe the | character - e.g.
438 to create an OR match. Matches can be nested with () - e.g.
440 sub ((GET|POST) + /user/*) {
442 and negated with ! - e.g.
444 sub (!/user/foo + /user/*) {
446 ! binds to the immediate rightmost match specification, so if you want
447 to negate a combination you will need to use
449 sub ( !(POST|PUT|DELETE) ) {
451 and | binds tighter than +, so
453 sub ((GET|POST) + /user/*) {
457 sub (GET|POST + /user/*) {
461 sub ((GET + .html) | (POST + .html)) {
465 sub (GET + .html | POST + .html) {
467 are not - the latter is equivalent to
469 sub (GET + (.html|POST) + .html) {
471 which will never match.
475 Note that for legibility you are permitted to use whitespace -
477 sub (GET + /user/*) {
479 but it will be ignored. This is because the perl parser strips whitespace
480 from subroutine prototypes, so this is equivalent to