summaryrefslogtreecommitdiffstats
path: root/lib/Jaos/WebApp.pm
blob: 4d57a9426271674f15fdbfacf447bdfc0f1e2760 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package Jaos::WebApp;
use strict;
use warnings;
our $VERSION = 0.3;
use Jaos::WebApp::Dispatcher;
use Jaos::WebApp::Route;
use Jaos::WebApp::Log;
use Plack::Request;
use File::Find::Rule;

sub new
{
  my $class = shift;
  my ($package, $script) = caller;
  my $appdir = File::Basename::dirname(File::Spec->rel2abs($script));

  my $self  = {
    dispatcher   => Jaos::WebApp::Dispatcher->new(),
    route_hooks  => {},
    run_hooks    => {},
    render_hooks => {},
    renderers    => {},
    appdir       => $appdir,
    log          => Jaos::WebApp::Log->new(@_),
    req => undef, res => undef, stash => undef,
  };

  bless $self, $class;

  # load our modules
  undef $@;
  eval {
    my $path = "$appdir/lib/";
    my @submods = map { s|$path||g; s|/|::|g; s|.pm||; $_; }
                  File::Find::Rule->file()->name('*.pm')
                  ->in($path . $class);
    for my $m (@submods) {
      eval "require $m" or die "Failed to load $m: $!";
    }
  };
  if ($@) {
    $self->log->error("$@");
    return $self->internal_server_error("$@");
  }


  $self->startup;

  $self;
}

sub connect
{
  my $self = shift;
  $self->{dispatcher}->connect(@_);
}

sub log { shift->{log}; }
sub stash { shift->{stash}; }
sub req { shift->{req}; }
sub res { shift->{res}; }

sub run
{
  my $self = shift;
  my $env  = shift;

  $self->log->debug("setting up request and response objects");
  my $req = Plack::Request->new($env);
  my $res = $req->new_response;

  $self->{stash} = { session => {} };
  $self->{req}   = $req;
  $self->{res}   = $res;

  # pre dispatch hook here
  $self->log->debug("running pre dispatch hooks");
  $_->($self) for @{$self->{run_hooks}->{pre_dispatch} || []};

  eval {
    if (my $rule = $self->{dispatcher}->match($self)) {
      my $controller_class  = $rule->controller;
      my $action            = $rule->action;
      my $controller        = $controller_class->new($self);

      $self->log->debug("Found $controller_class:$action for " . $self->req->path_info);

      $controller->$action;
      $res->status(200) if !$res->status;

    } else {
      $self->log->info("unable to find route for " . $self->req->path_info);
      $self->not_found($req, $res);
    }
  };
  if ($@) {
    $self->log->error("dispatch error: $@");
    $self->internal_server_error("$@", $req, $res);
  }

  # post dispatch hook here
  $self->log->debug("running post dispatch hooks");
  $_->($self) for reverse @{$self->{run_hooks}->{post_dispatch} || []};

  delete $self->{ qw/stash res req/};
  return $res->finalize;
}


sub internal_server_error
{
  my ($self, $err, $req, $res) = @_;
  if (defined $self->{res}) {
    $res->status(500);
    $res->body("ERROR: $err");
  } else {
    die $err;
  }
}

sub not_found
{
  my ($self, $req, $res) = @_;
  $res->status(404);
  $res->body("Not Found");
}

sub add_route_hook
{
  my ($self, $name, $sub) = @_;
  $self->log->debug("adding route hook $name");
  $self->{route_hooks}->{$name} = $sub; 
}

sub add_run_hook
{
  my ($self, $name, $sub) = @_;
  $self->log->debug("adding run hook $name");
  push @{$self->{run_hooks}->{$name}}, $sub; 
}

sub add_renderer
{
  my ($self, $name, $sub) = @_;
  $self->log->debug("adding renderer $name");
  $self->{renderers}->{$name} = $sub; 
}

sub renderer
{
  my ($self, $handler) = @_;
  $self->{renderers}->{$handler};
}

sub load_plugin
{
  my ($self, $plugin_class, $opts) = @_;
  $self->log->debug("loading plugin $plugin_class");
  eval {
    if (!$plugin_class->can('register')) {
      eval "require $plugin_class";
    }
    $plugin_class->register($self, $opts);
  };
  if ($@) {
    die "Failed to load plugin $plugin_class: $@";
  }
  1;
}

sub appdir
{
  shift->{appdir};
}

sub startup
{
  my $self = shift;
}

=head1 NAME

Jaos::WebApp - Minimal web application framework

=head1 SYNOPSIS

 package MyApp;
 use base qw(Jaos::WebApp);
 sub startup {
   my $app = shift;
   $app->load_plugin('Jaos::WebApp::Route::MethodConstraint');
   $app->load_plugin('Jaos::WebApp::Route::ParamConstraint');
   $app->load_plugin('Jaos::WebApp::Route::HeaderConstraint');
   $app->load_plugin('Jaos::WebApp::Render::TT');
   $app->connect('/about', controller => 'MyApp::Controller', action => 'about');
   $app->connect('/login', controller => 'MyApp::Controller', action => 'login', method => 'post');
   $app->connect('/',      controller => 'MyApp::Controller', action => 'frontpage');
 }
 1;

 # Later, in your application.psgi file...
 # See C<Jaos::WebApp::Log> for logging configuration
 use lib './lib';
 use MyApp;
 my $app = MyApp->new( loglevel => 'info', logfile => '/path/to/log');
 sub { $app->run(@_); };

=head1 DESCRIPTION

This is a minimal web application framework designed to be deployed on top of L<Plack>.  It has no non-CORE module requirements and is very minimal.  Additional functionality can be added by extending the framework through plugins.

=head1 DEPLOYING

Here are some examples of how to deploy the application with Plack.

=head2 Apache2/mod_perl

 <IfModule mod_perl.c>
   <Perl>
      use Plack::Handler::Apache2;
      Plack::Handler::Apache2->preload("/path/to/application.psgi");
   </Perl>
   <Location />
     SetHandler perl-script
     PerlResponseHandler Plack::Handler::Apache2
     PerlSetVar psgi_app /path/to/application.psgi
   </Location>
 </IfModule>

=head2 plackup command line utility to run PSGI applications

 plackup application.psgi

=head1 METHODS

=head2 new

Constructor.  This sets up the default dispatcher and attempts to load all modules found within ./lib of the app directory.

Calls the startup method for subclass/application specific setup.

=head2 appdir

Returns the base directory in which the application is running.

=head2 startup

Method for setting up application specific configuration, overridden by derived application classes.

=head2 connect

Connect given path and options to a L<Jaos::WebApp::Route> object by the composed L<Jaos::WebApp::Dispatcher> object.

=head2 stash

Returns a hashref for per request storage

=head2 req

Shortcut to the L<Plack::Request> object.

=head2 res

Shortcut to the L<Plack::Response> object.

=head2 run

This is the request handler that is passed a L<PSGI> environment from which a L<Plack::Request> object is created.

The dispatcher matches the request path to a route and fires off B<pre_dispatch> and B<post_dispatch> hooks before and after the controller action method.

=head2 load_plugin

Load the specified class and call its B<register> method.

=head2 add_route_hook

This is called during plugin register to add a route hook callback.  See L<Jaos::WebApp::Route>.

=head2 add_run_hook

This is called during plugin register to add a run hook callback.  Currently only B<pre_dispatch> and B<post_dispatch> hooks are availabl.e

=head2 add_renderer

This is called during plugin register to add a renderer type callback.  See L<Jaos::WebApp::Render>.

=head2 renderer

Returns the callback for the named renderer.

=head2 internal_server_error

This is called on error, passing in the error and the request and response objects (if available at the time of the error).  This is easily overridden by the application derived class.

=head2 not_found

This is called when no matching route can be found.  The request and response objects are passed as arguments.  This is easily overridden by the application derived class.

=head1 SEE ALSO

L<Plack>, L<Plack::Request>, L<Plack::Response>

=head1 AUTHOR

Jason Woodward <woodwardj@jaos.org>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;