5 use warnings::illegalproto ();
7 our $VERSION = '0.004';
10 my ($class, $app_package) = @_;
11 $class->_export_into($app_package||caller);
12 eval "package $class; use Web::Dispatch::Wrapper; use Moo;";
14 warnings::illegalproto->unimport;
18 my ($class, $app_package) = @_;
21 *{"${app_package}::PSGI_ENV"} = sub () { -1 };
22 require Web::Simple::Application;
23 unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
25 (my $name = $app_package) =~ s/::/\//g;
26 $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
31 Web::Simple - A quick and easy way to build simple web applications
35 This is really quite new. If you're reading this on CPAN, it means the stuff
36 that's here we're probably happy with. But only probably. So we may have to
37 change stuff. And if you're reading this from git, come check with irc.perl.org
38 #web-simple that we're actually sure we're going to keep anything that's
39 different from the CPAN version.
41 If we do find we have to change stuff we'll add to the
42 L<CHANGES BETWEEN RELEASES> section explaining how to switch your code across
43 to the new version, and we'll do our best to make it as painless as possible
44 because we've got Web::Simple applications too. But we can't promise not to
45 change things at all. Not yet. Sorry.
51 use Web::Simple 'HelloWorld';
56 sub dispatch_request {
58 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
61 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
66 HelloWorld->run_if_script;
68 If you save this file into your cgi-bin as hello-world.cgi and then visit
70 http://my.server.name/cgi-bin/hello-world.cgi/
72 you'll get the "Hello world!" string output to your browser. For more complex
73 examples and non-CGI deployment, see below. To get help with Web::Simple,
74 please connect to the irc.perl.org IRC network and join #web-simple.
78 Web::Simple was originally written to form part of my Antiquated Perl talk for
79 Italian Perl Workshop 2009, but in writing the bloggery example I realised
80 that having a bare minimum system for writing web applications that doesn't
81 drive me insane was rather nice and decided to spend my attempt at nanowrimo
82 for 2009 improving and documenting it to the point where others could use it.
84 The philosophy of Web::Simple is to keep to an absolute bare minimum, for
85 everything. It is not designed to be used for large scale applications;
86 the L<Catalyst> web framework already works very nicely for that and is
87 a far more mature, well supported piece of software.
89 However, if you have an application that only does a couple of things, and
90 want to not have to think about complexities of deployment, then Web::Simple
91 might be just the thing for you.
93 The Antiquated Perl talk can be found at L<http://www.shadowcat.co.uk/archive/conference-video/>.
97 The only public interface the Web::Simple module itself provides is an
100 use Web::Simple 'NameOfApplication';
102 This imports 'strict' and 'warnings FATAL => "all"' into your code as well,
103 so you can skip the usual
108 provided you 'use Web::Simple' at the top of the file. Note that we turn
109 on *fatal* warnings so if you have any warnings at any point from the file
110 that you did 'use Web::Simple' in, then your application will die. This is,
111 so far, considered a feature.
113 Calling the import also makes NameOfApplication isa Web::Simple::Application
114 and sets your app class up as a L<Moo> class- i.e. does the equivalent of
117 package NameOfApplication;
119 extends 'Web::Simple::Application';
122 It also exports the following subroutines for use in dispatchers:
124 response_filter { ... };
126 redispatch_to '/somewhere';
130 $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
132 so that perl will not attempt to load the application again even if
134 require NameOfApplication;
136 is encountered in other code.
138 =head1 DISPATCH STRATEGY
142 sub dispatch_request {
143 # matches: GET /user/1.htm?show_details=1
145 sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
146 my ($self, $user_id, $show_details) = @_;
149 # matches: POST /user?username=frew
150 # POST /user?username=mst&first_name=matt&last_name=trout
151 sub (POST + /user + ?username=&*) {
152 my ($self, $username, $misc_params) = @_;
155 # matches: DELETE /user/1/friend/2
156 sub (DELETE + /user/*/friend/*) {
157 my ($self, $user_id, $friend_id) = @_;
160 # matches: PUT /user/1?first_name=Matt&last_name=Trout
161 sub (PUT + /user/* + ?first_name~&last_name~) {
162 my ($self, $user_id, $first_name, $last_name) = @_;
167 # matches: PUT /user/1/role/1
168 sub (PUT + /role/*) {
172 # matches: DELETE /user/1/role/1
173 sub (DELETE + /role/*) {
180 =head2 The dispatch cycle
182 At the beginning of a request, your app's dispatch_request method is called
183 with the PSGI $env as an argument. You can handle the request entirely in
184 here and return a PSGI response arrayref if you want:
186 sub dispatch_request {
187 my ($self, $env) = @_;
188 [ 404, [ 'Content-type' => 'text/plain' ], [ 'Amnesia == fail' ] ]
191 However, generally, instead of that, you return a set of dispatch subs:
193 sub dispatch_request {
195 sub (/) { redispatch_to '/index.html' },
196 sub (/user/*) { $self->show_user($_[1]) },
200 If you return a subroutine with a prototype, the prototype is treated
201 as a match specification - and if the test is passed, the body of the
202 sub is called as a method any matched arguments (see below for more details).
204 You can also return a plain subroutine which will be called with just $env
205 - remember that in this case if you need $self you -must- close over it.
207 If you return a normal object, Web::Simple will simply return it upwards on
208 the assumption that a response_filter somewhere will convert it to something
209 useful - this allows:
211 sub dispatch_request {
213 sub (.html) { response_filter { $self->render_zoom($_[0]) } },
214 sub (/user/*) { $self->users->get($_[1]) },
217 to render a user object to HTML, for example.
219 However, two types of object are treated specially - a Plack::App object
220 will have its ->to_app method called and be used as a dispatcher:
222 sub dispatch_request {
224 sub (/static/...) { Plack::App::File->new(...) },
228 A Plack::Middleware object will be used as a filter for the rest of the
229 dispatch being returned into:
231 sub dispatch_request {
234 sub (/admin) { Plack::Middleware::Session->new(...) },
235 ... # dispatchers needing a session go here
238 Note that this is for the dispatch being -returned- to, so if you want to
239 provide it inline you need to do:
241 sub dispatch_request {
245 sub { Plack::Middleware::Session->new(...) },
246 ... # dispatchers under /admin
250 And that's it - but remember that all this happens recursively - it's
251 dispatchers all the way down.
253 =head2 Web::Simple match specifications
255 =head3 Method matches
259 A match specification beginning with a capital letter matches HTTP requests
260 with that request method.
266 A match specification beginning with a / is a path match. In the simplest
267 case it matches a specific path. To match a path with a wildcard part, you
271 $self->handle_user($_[1])
273 This will match /user/<anything> where <anything> does not include a literal
274 / character. The matched part becomes part of the match arguments. You can
275 also match more than one part:
278 my ($self, $user_1, $user_2) = @_;
280 sub (/domain/*/user/*) {
281 my ($self, $domain, $user) = @_;
283 and so on. To match an arbitrary number of parts, use -
287 This will result in an element per /-separated part so matched. Note that
290 sub (/page/**/edit) {
292 to match an arbitrary number of parts up to but not including some final
299 will match /foo/ on the beginning of the path -and- strip it, much like
300 .html strips the extension. This is designed to be used to construct
301 nested dispatch structures, but can also prove useful for having e.g. an
302 optional language specification at the start of a path.
304 Note that the '...' is a "maybe something here, maybe not" so the above
305 specification will match like this:
308 /foo/ # match and strip path to '/'
309 /foo/bar/baz # match and strip path to '/bar/baz'
311 =head3 Extension matches
315 will match and strip .html from the path (assuming the subroutine itself
316 returns something, of course). This is normally used for rendering - e.g.
319 response_filter { $self->render_html($_[1]) }
326 will match any extension and supplies the stripped extension as a match
329 =head3 Query and body parameter matches
331 Query and body parameters can be match via
333 sub (?<param spec>) { # match URI query
334 sub (%<param spec>) { # match body params
336 The body is only matched if the content type is
337 application/x-www-form-urlencoded (note this means that Web::Simple does
338 not yet handle uploads; this will be addressed in a later release).
340 The param spec is elements of one of the following forms -
342 param~ # optional parameter
343 param= # required parameter
344 @param~ # optional multiple parameter
345 @param= # required multiple parameter
346 :param~ # optional parameter in hashref
347 :param= # required parameter in hashref
348 :@param~ # optional multiple in hashref
349 :@param= # required multiple in hashref
350 * # include all other parameters in hashref
351 @* # include all other parameters as multiple in hashref
353 separated by the & character. The arguments added to the request are
354 one per non-:/* parameter (scalar for normal, arrayref for multiple),
355 plus if any :/* specs exist a hashref containing those values.
357 So, to match a page parameter with an optional order_by parameter one
360 sub (?page=&order_by~) {
361 my ($self, $page, $order_by) = @_;
362 return unless $page =~ /^\d+$/;
365 $_[1]->search_rs({}, $p);
369 to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
371 Note that if a parameter is specified as single and multiple values are found,
372 the last one will be used.
374 To get all parameters as a hashref of arrayrefs, write:
377 my ($self, $params) = @_;
380 To get two parameters as a hashref, write:
382 sub(?:user~&:domain~) {
383 my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
385 You can also mix these, so:
387 sub (?foo=&@bar~&:coffee=&@*) {
388 my ($self, $foo, $bar, $params);
390 where $bar is an arrayref (possibly an empty one), and $params contains
391 arrayref values for all parameters -not- mentioned and a scalar value for
392 the 'coffee' parameter.
394 =head3 Combining matches
396 Matches may be combined with the + character - e.g.
398 sub (GET + /user/*) {
400 to create an AND match. They may also be combined withe the | character - e.g.
404 to create an OR match. Matches can be nested with () - e.g.
406 sub ((GET|POST) + /user/*) {
408 and negated with ! - e.g.
410 sub (!/user/foo + /user/*) {
412 ! binds to the immediate rightmost match specification, so if you want
413 to negate a combination you will need to use
415 sub ( !(POST|PUT|DELETE) ) {
417 and | binds tighter than +, so
419 sub ((GET|POST) + /user/*) {
423 sub (GET|POST + /user/*) {
427 sub ((GET + .html) | (POST + .html)) {
431 sub (GET + .html | POST + .html) {
433 are not - the latter is equivalent to
435 sub (GET + (.html|POST) + .html) {
437 which will never match.
441 Note that for legibility you are permitted to use whitespace -
443 sub (GET + /user/*) {
445 but it will be ignored. This is because the perl parser strips whitespace
446 from subroutine prototypes, so this is equivalent to
450 =head3 Accessing the PSGI env hash
452 In some cases you may wish to get the raw PSGI env hash - to do this,
453 you can either use a plain sub -
460 or use the PSGI_ENV constant exported to retrieve it:
462 sub (GET + /foo + ?some_param=) {
464 my $env = $_[PSGI_ENV];
467 but note that if you're trying to add a middleware, you should simply use
468 Web::Simple's direct support for doing so.
470 =head1 EXPORTED SUBROUTINES
472 =head2 response_filter
475 # Hide errors from the user because we hates them, preciousss
476 if (ref($_[0]) eq 'ARRAY' && $_[0]->[0] == 500) {
477 $_[0] = [ 200, @{$_[0]}[1..$#{$_[0]}] ];
482 The response_filter subroutine is designed for use inside dispatch subroutines.
484 It creates and returns a special dispatcher that always matches, and calls
485 the block passed to it as a filter on the result of running the rest of the
486 current dispatch chain.
488 Thus the filter above runs further dispatch as normal, but if the result of
489 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
490 response without altering the headers or body.
494 redispatch_to '/other/url';
496 The redispatch_to subroutine is designed for use inside dispatch subroutines.
498 It creates and returns a special dispatcher that always matches, and instead
499 of continuing dispatch re-delegates it to the start of the dispatch process,
500 but with the path of the request altered to the supplied URL.
502 Thus if you receive a POST to '/some/url' and return a redispatch to
503 '/other/url', the dispatch behaviour will be exactly as if the same POST
504 request had been made to '/other/url' instead.
506 =head1 CHANGES BETWEEN RELEASES
508 =head2 Changes between 0.004 and 0.005
512 =item * dispatch {} replaced by declaring a dispatch_request method
514 dispatch {} has gone away - instead, you write:
516 sub dispatch_request {
518 sub (GET /foo/) { ... },
522 Note that this method is still -returning- the dispatch code - just like
525 Also note that you need the 'my $self = shift' since the magic $self
528 =item * the magic $self variable went away.
530 Just add 'my $self = shift;' while writing your 'sub dispatch_request {'
531 like a normal perl method.
533 =item * subdispatch deleted - all dispatchers can now subdispatch
535 In earlier releases you needed to write:
537 subdispatch sub (/foo/...) {
540 sub (GET /bar/) { ... },
545 As of 0.005, you can instead write simply:
550 sub (GET /bar/) { ... },
555 =head2 Changes since Antiquated Perl
559 =item * filter_response renamed to response_filter
561 This is a pure rename; a global search and replace should fix it.
563 =item * dispatch [] changed to dispatch {}
567 dispatch [ sub(...) { ... }, ... ];
571 dispatch { sub(...) { ... }, ... };
577 =head1 COMMUNITY AND SUPPORT
581 irc.perl.org #web-simple
583 =head2 No mailing list yet
585 Because mst's non-work email is a bombsite so he'd never read it anyway.
587 =head2 Git repository
589 Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
591 git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
595 Matt S. Trout <mst@shadowcat.co.uk>
599 None required yet. Maybe this module is perfect (hahahahaha ...).
603 Copyright (c) 2009 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
608 This library is free software and may be distributed under the same terms