d3806df81a5542d9bb4b7f0117b11c444bd917f1
[catagits/Web-Simple.git] / lib / Web / Simple / Application.pm
1 package Web::Simple::Application;
2
3 use Moo;
4
5 has 'config' => (
6   is => 'ro',
7   default => sub {
8     my ($self) = @_;
9     +{ $self->default_config }
10   },
11   trigger => sub {
12     my ($self, $value) = @_;
13     my %default = $self->default_config;
14     my @not = grep !exists $value->{$_}, keys %default;
15     @{$value}{@not} = @default{@not};
16   }
17 );
18
19 sub default_config { () }
20
21 has '_dispatcher' => (is => 'lazy');
22
23 sub _build__dispatcher {
24   my $self = shift;
25   require Web::Dispatch;
26   require Web::Simple::DispatchNode;
27   my $final = $self->_build_final_dispatcher;
28   Web::Dispatch->new(
29     app => sub { $self->dispatch_request(@_), $final },
30     node_class => 'Web::Simple::DispatchNode',
31     node_args => { app_object => $self }
32   );
33 }
34
35 sub _build_final_dispatcher {
36   [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
37 }
38
39 sub run_if_script {
40   # ->to_psgi_app is true for require() but also works for plackup
41   return $_[0]->to_psgi_app if caller(1);
42   my $self = ref($_[0]) ? $_[0] : $_[0]->new;
43   $self->run(@_);
44 }
45
46 sub _run_cgi {
47   my $self = shift;
48   require Plack::Server::CGI;
49   Plack::Server::CGI->run($self->to_psgi_app);
50 }
51
52 sub _run_fcgi {
53   my $self = shift;
54   require Plack::Server::FCGI;
55   Plack::Server::FCGI->run($self->to_psgi_app);
56 }
57
58 sub to_psgi_app {
59   my $self = ref($_[0]) ? $_[0] : $_[0]->new;
60   $self->_dispatcher->to_app;
61 }
62
63 sub run {
64   my $self = shift;
65   if ($ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH}) {
66     return $self->_run_fcgi;
67   } elsif ($ENV{GATEWAY_INTERFACE}) {
68     return $self->_run_cgi;
69   }
70   unless (@ARGV && $ARGV[0] =~ m{^[A-Z/]}) {
71     return $self->_run_cli(@ARGV);
72   }
73
74   my @args = @ARGV;
75
76   unshift(@args, 'GET') if $args[0] =~ m{^/};
77
78   $self->_run_test_request(@args);
79 }
80
81 sub _run_test_request {
82   my ($self, $method, $path, @rest) = @_;
83
84   require HTTP::Request;
85   require Plack::Test;
86
87   my $request = HTTP::Request->new($method => $path);
88   if ($method eq 'POST' or $method eq 'PUT' and @rest) {
89     my $content = do {
90       require URI;
91       my $url = URI->new('http:');
92       $url->query_form(@rest);
93       $url->query;
94     };
95     $request->header('Content-Type' => 'application/x-www-form-urlencoded');
96     $request->header('Content-Length' => length($content));
97     $request->content($content);
98   }
99   my $response;
100   Plack::Test::test_psgi(
101     $self->to_psgi_app, sub { $response = shift->($request) }
102   );
103   print $response->as_string;
104 }
105
106 sub _run_cli {
107   my $self = shift;
108   die $self->_cli_usage;
109 }
110
111 sub _cli_usage {
112   "To run this script in CGI test mode, pass a URL path beginning with /:\n".
113   "\n".
114   "  $0 /some/path\n".
115   "  $0 /\n"
116 }
117
118 1;
119
120 =head1 NAME
121
122 Web::Simple::Application - A base class for your Web-Simple application
123
124 =head1 DESCRIPTION
125
126 This is a base class for your L<Web::Simple> application.  You probably don't
127 need to construct this class yourself, since L<Web::Simple> does the 'heavy
128 lifting' for you in that regards.
129
130 =head1 METHODS
131
132 This class exposes the following public methods.
133
134 =head2 default_config
135
136 Merges with the C<config> initializer to provide configuration information for
137 your application.  For example:
138
139   sub default_config {
140     (
141       title => 'Bloggery',
142       posts_dir => $FindBin::Bin.'/posts',
143     );
144   }
145
146 Now, the C<config> attribute of C<$self>  will be set to a HashRef
147 containing keys 'title' and 'posts_dir'.
148
149 The keys from default_config are merged into any config supplied, so
150 if you construct your application like:
151
152   MyWebSimpleApp::Web->new(
153     config => { title => 'Spoon', environment => 'dev' }
154   )
155
156 then C<config> will contain:
157
158   {
159     title => 'Spoon',
160     posts_dir => '/path/to/myapp/posts',
161     environment => 'dev'
162   }
163
164 =head2 run_if_script
165
166 The run_if_script method is designed to be used at the end of the script
167 or .pm file where your application class is defined - for example:
168
169   ## my_web_simple_app.pl
170   #!/usr/bin/env perl
171   use Web::Simple 'HelloWorld';
172
173   {
174     package HelloWorld;
175
176     sub dispatch_request {
177       sub (GET) {
178         [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
179       },
180       sub () {
181         [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
182       }
183     }
184   }
185
186   HelloWorld->run_if_script;
187
188 This returns a true value, so your file is now valid as a module - so
189
190   require 'my_web_simple_app.pl';
191
192   my $hw = HelloWorld->new;
193
194 will work fine (and you can rename it to lib/HelloWorld.pm later to make it
195 a real use-able module).
196
197 However, it detects if it's being run as a script (via testing $0) and if
198 so attempts to do the right thing.
199
200 If run under a CGI environment, your application will execute as a CGI.
201
202 If run under a FastCGI environment, your application will execute as a
203 FastCGI process (this works both for dynamic shared-hosting-style FastCGI
204 and for apache FastCgiServer style setups).
205
206 If run from the commandline with a URL path, it runs a GET request against
207 that path -
208
209   $ perl -Ilib examples/hello-world/hello-world.cgi /
210   200 OK
211   Content-Type: text/plain
212   
213   Hello world!
214
215 Additionally, you can treat the file as though it were a standard PSGI
216 application file (*.psgi).  For example you can start up up with C<plackup>
217
218   plackup my_web_simple_app.pl
219
220 or C<starman>
221
222   starman my_web_simple_app.pl
223
224 =head2 to_psgi_app
225
226 This method is called by L</run_if_script> to create the L<PSGI> app coderef
227 for use via L<Plack> and L<plackup>. If you want to globally add middleware,
228 you can override this method:
229
230   use Web::Simple 'HelloWorld';
231   use Plack::Builder;
232  
233   {
234     package HelloWorld;
235
236   
237     around 'to_psgi_app', sub {
238       my ($orig, $self) = (shift, shift);
239       my $app = $self->$orig(@_); 
240       builder {
241         enable ...; ## whatever middleware you want
242         $app;
243       };
244     };
245   }
246
247 This method can also be used to mount a Web::Simple application within
248 a separate C<*.psgi> file -
249
250   use strictures 1;
251   use Plack::Builder;
252   use WSApp;
253   use AnotherWSApp;
254
255   builder {
256     mount '/' => WSApp->to_psgi_app;
257     mount '/another' => AnotherWSApp->to_psgi_app;
258   };
259
260 This method can be called as a class method, in which case it implicitly
261 calls ->new, or as an object method ... in which case it doesn't.
262
263 =head2 run
264
265 Used for running your application under stand-alone CGI and FCGI modes. Also
266 useful for testing:
267
268     my $app = MyWebSimpleApp::Web->new;
269     my $c = HTTP::Request::AsCGI->new(@args)->setup;
270     $app->run;
271
272 =head1 AUTHORS
273
274 See L<Web::Simple> for authors.
275
276 =head1 COPYRIGHT AND LICENSE
277
278 See L<Web::Simple> for the copyright and license.
279
280 =cut