blib/lib/Magpie.pm

filter: Statementstmt 100% 5 / 5 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 1 / 1 Podpod n/a totaltotal 100% 6 / 6 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
CRAP 1.0
« blib/lib/Magpie/Machine.pm ↑ Summary blib/lib/Magpie/Error.pm »
1 package Magpie;
2 1 $Magpie::VERSION = '1.141660';
3 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 # ABSTRACT: Pipelined State Machine Plack Middleware Framework
6  
7 1 1;
8  
9  
10 =pod
11  
12 =head1 NAME
13  
14 Magpie - Pipelined State Machine Plack Middleware Framework
15  
16 =head1 VERSION
17  
18 version 1.141660
19  
20 =head1 SYNOPSIS
21  
22 -----
23 # static.psgi
24 use Plack::Builder
25 use Plack::Middleware::Magpie;
26  
27 # A static pipeline, will always load the same components
28 # for every request,
29 my $app = builder {
30 enable "Magpie", context => {}, pipeline => [
31 # main application logic
32 'MyApp::Core',
33  
34 # transform the result using Template Toolkit
35 'Magpie::Transformer::TT2' => { template_root => '/my/template/dir' }
36 ];
37 };
38  
39 -----
40 # dynamic.psgi
41 use Plack::Builder
42 use Plack::Middleware::Magpie;
43  
44 # use the machine and match, and match_env sugar to load components
45 # conditionally
46 my $app = builder {
47 enable "Magpie", context => {}, pipeline => [
48 machine {
49 # prepend an input transformer for POST and PUT requests
50 match_env { REQUEST_METHOD => qr/POST|PUT/ } => ['MyApp::InputHandler'];
51  
52 # matches every request, generates core content
53 match qr|^/| => ['MyApp::XMLGenerator];
54  
55 # apply different XSLT stylesheets based on the request path.
56 match qr|^/blog/| => [ 'Magpie::Transformer::XSLT'
57 => { stylesheet => '/style/blog.xsl'}];
58  
59 match qr|^/shop/| => [ 'Magpie::Transformer::XSLT'
60 => { stylesheet => '/style/cart.xsl'}];
61 }
62 ];
63 };
64  
65 =head1 How Does Magpie Work?
66  
67 =for html <img src="images/Magpiebasicflow.png" alt="Magpie's Basic Application Flow"/>
68  
69 A typical Magpie application has three parts:
70  
71 =over
72  
73 =item 1
74  
75 One or more L<Application Classes|/Application Classes> that contain the event
76 handler methods that are fired during the application's run.
77  
78 =item 2
79  
80 One or more L<Output Class|/Output Classes> that controls how to serialize the
81 application state into data that the requesting client can consume.
82  
83 =item 3
84  
85 An L<interface script/module|/interface script/module> that constructs the
86 L<Magpie::Machine> application pipeline and connects it to the wider world.
87  
88 =back
89  
90 =head2 External Interfaces
91  
92 First, the I<interface> component:
93  
94 # sample.pm -- A Typical Magpie application as a modperl2 handler
95 package sample::handler;
96 use Magpie::Machine;
97 use Apache::Response;
98 use Apache::Const;
99  
100  
101 sub handler {
102 my $r = shift;
103  
104 # load the Application and Output classes into
105 # the Magpie pipeline
106 my $app = Magpie::Machine->new();
107 $app->pipeline( qw(
108 My::Greetings
109 Magpie::Output::Scalar
110 ) );
111  
112 # can be any type of Perl reference or object
113 my $application_context = {};
114  
115 # execute the application pipeline
116 return $app->run( $application_context );
117 }
118  
119 1;
120  
121 Like all ModPerl content handlers, this simple module implements a
122 C<handler()> method that is called whenever the URI associated with this
123 module is requested. Here, that method creates a new Magpie application by
124 calling the C<new()> constructor of the C<Magpie::Machine> class-- all Magpie
125 applications are an instance of that class.
126  
127 By itself, this instance of the Machine class does nothing useful; we must
128 load the L<Application Class|/Application Classes> (or classes) that will
129 perform required operations and the L<Output Class|/Output Classes> that will
130 generate the appropriate response. We do this by calling the Machine
131 instance's C<pipeline()> method and passing in a list containing a mix of
132 either the I<Perl package names> of the classes we want to load or I<blessed
133 instances> of those classes. In the example above, we loaded two classes into
134 the Machine's application pipeline: C<My::Greetings> and
135 C<Magpie::Output::Scalar> by simply passing in the class names.
136  
137 Finally, we set the application in motion by calling the Machine instance's
138 C<run()> method. This method takes a single argument that may contain any sort
139 of Perl reference (hash reference, array reference, blessed object). and,
140 whatever data structure or object that is passed as that argument is made
141 available to all methods in the Application and Output classes that are called
142 as the application runs (more about how this works in the L<next
143 section|/Application Classes>). When the C<run()> method is called, each class
144 that was passed in via the C<pipeline()> method is loaded in the order they we
145 passed and all I<event handler> methods implemented in those classes that
146 match the current application state are called. When the event handlers from
147 one application class are completed the Machine loads the next class and calls
148 its methods-- and so on, until the last method in the Output class is called,
149 at which point the response has been sent and the application pipeline
150 terminates.
151  
152 =head1 Application Classes
153  
154 In Magpie, application classes are implemented as subclasses of an event
155 model. This underlying Event class is responsible for registering event
156 handlers with Magpie's internal queue and for determining which of those
157 registered handlers will be fired in response to the current state. In short,
158 the Event class determines which state the application is in, and which of the
159 registered event handler methods will be fired in response to that state.
160 Usually, the details of mapping states to events are never visible to the
161 developer beyond the initial choice of which Event model to use as a base
162 class (different Event classes use different conditions to determine
163 application state). In daily practice, you simply implement and register the
164 events that you application needs and let Magpie do the rest.
165  
166 # Greetings.pm -- A Magpie Application class that greets the
167 # user based on application state
168 package MyApp::Pipeline::Greetings;
169 use Moose;
170  
171 # inherit from the base Component class.
172 extends 'Magpie::Component';
173  
174 # determines the application state based on the value
175 # of a specific form/query param ala CGI::Application.
176 with 'Magpie::Dispatcher::RequestParam' => { state_param => 'appstate' };
177  
178 # Import handler
179 use Magpie::Constants;
180  
181 # register the event handlers for this class
182 __PACKAGE__->register_events( qw( morning afternoon evening default) );
183  
184 # implement the event handlers
185  
186 sub morning {
187 my $self = shift;
188 my $ctxt = shift;
189  
190 $ctxt->{message} = 'Good morning!';
191  
192 return OK;
193 }
194  
195 sub afternoon {
196 my $self = shift;
197 my $ctxt = shift;
198  
199 $ctxt->{message} = 'Good afternoon!';
200  
201 return OK;
202 }
203  
204 sub evening {
205 my $self = shift;
206 my $ctxt = shift;
207  
208 $ctxt->{message} = 'Good evening!';
209  
210 return OK;
211 }
212  
213 # will be called if no matching state is found
214 sub default {
215 my $self = shift;
216 my $ctxt = shift;
217  
218 $ctxt->{message} = "I'm not sure what time of day it is!";
219  
220 return OK;
221 }
222  
223 1;
224  
225 First, notice that the application class is a subclass of the
226 C<Magpie::Component>. Through this interface (and the roles it consumes), you get access to the core attributes and methods of the Magpie application framework (see the section titled 'know thy $self' below). In C<Magpie::Event::Simple> you register
227 a list of state events via the required registerEvents() function. The event
228 model then determines which event handler method to fire by examining the
229 value of a specific querystring or POSTed form parameter. (The default param
230 is named "appstate" but that can be overridden by implementing the
231 C<state_param()> method and returning some other value). If the underlying
232 Event model finds a registered event whose name matches the value returned by
233 the C<state_param()> method, the event handler method named
234 C<event_B<<eventname>>> is called. So, for example, a request to the URI that
235 exposes the class above like the following:
236  
237 http://example.org/apps/greet?appstate=morning
238  
239 would cause the C<event_morning()> method to be called. If no matching state
240 is found, the C<event_default()> event handler method is called as a fallback.
241 In addition, most Magpie Event model classes also implement an C<event_init()>
242 handler and an C<event_exit()> handler. These methods are optional and, if
243 implemented, C<event_init()> will be called after the event queue is
244 initialized but before the first state-determined event handler is fired while
245 C<event_exit()> is called just before the application exits.
246  
247 Note that C<Magpie::Event::Simple> (that determines application state based on
248 a single form param) is only one possible event model and you are free to
249 choose another and/or write your own-- even mixing application classes based
250 on different models within the same application pipeline. This flexibility is
251 one of Magpie's key strengths.
252  
253 =head2 Event Handler Methods
254  
255 Every Magpie Application class will implement one or more I<event handler
256 methods> that will be called conditionally based on the state that is
257 determined by the underlying event model. It is within these methods that the
258 real business of the application takes place. In the above example, these
259 methods merely set a key in the application-wide C<$ctxt> hash reference, but
260 there is no limit to what you can do. Remember, part of the point of Magpie is
261 to separate state detection from application code-- this is achieved by having
262 the event model parent class determine the state then call the event handler
263 methods that implement the code that should be run for that state.
264  
265 Each event handler method is passed two arguments: the C<$self> class instance
266 member, and a special I<application context> member (named C<$ctxt> in the
267 examples above).
268  
269 =head3 Know Thy $self
270  
271 In Magpie Application classes the C<$self> class instance member offers access to a handful of common attributes and methods:
272  
273 =over
274  
275 =item C<< B<< $self->request >> >>
276  
277 This offers acccess to C<Plack::Request> object representing the current client request.
278  
279 Example:
280  
281 if ( $self->request->method eq 'POST' ) {
282 ...
283 }
284  
285 =back
286  
287 =head3 Keeping Things In $ctxt
288  
289 The second argument passed to each event handler method is the I<context
290 member> (named $ctxt in these examples). The context member-- which can be any
291 kind of Perl object or reference to another data structure-- is passed as the
292 sole argument to the application pipeline's run() method.
293  
294 # in your interface module/script:
295 my $handler = builder {
296 enable "Magpie", context => $app_context, pipeline => [
297 ...
298 ];
299 };
300 ...
301  
302 # then later, in the event handler methods in your application classes
303 sub myevent {
304 my $self = shift;
305 my $ctxt = shift; # same object/data as $app_context above
306 }
307  
308 In keeping with Magpie's general goal of letting developers do what makes the
309 most sense to them, Magpie does not enforce many rules about what the $ctxt
310 can be, or how it can be used. The only constraint is that the context member
311 I<must> be a scalar or reference. Typically, the context member is a reference
312 to a Perl hash, an anonymous hash reference, or a blessed object. Again, some
313 examples that might appear in your in your interface module/script:
314  
315 # use a reference to an existing hash
316 my %context = (
317 template_dir => '/usr/local/my/app/templates',
318 default_template => 'index.xsl',
319 );
320  
321 my $handler = builder {
322 enable "Magpie", context => \%context, pipeline => [
323 ...
324 ];
325 };
326  
327 # some advanced apps do well to make the context an object
328 # that implements is own set of methods
329 my $context = My::Application::ContextMember->new( %args );
330  
331 my $handler = builder {
332 enable "Magpie", context => $context, pipeline => [
333 ...
334 ];
335 };
336  
337 When no context member is explicitly passed into the Magpie machine an anonymous hash reference is used as a fallback.
338  
339 # no $ctxt is passed in
340 my $handler = builder {
341 enable "Magpie", pipeline => [
342 ...
343 ];
344 };
345  
346 # then later...
347 sub myevent {
348 my $self = shift;
349 my $ctxt = shift; # now an anonymous hashref
350 }
351  
352 Obviously, the role of the context member will vary greatly depending upon
353 your coding style and the needs of the application. In general, though, the
354 most common use of the $ctxt is to accumulate the data needed to render the
355 proper output for the current request. For example, if you are using the
356 Template Toolkit Transformer class (Magpie::Transformer::TT2) you might use a plain hash reference as the context member, then use it to capture the template name and variables that your templates depend on to deliver the content.
357  
358 =head2 Event Handler Return Codes
359  
360 Each event handler method must return one of a number of I<event handler
361 return codes>. The codes signal Magpie's internal event loop about what to do
362 after the current event handler method is finished. The codes themselves are
363 numeric, but are implemented as convenient Perl constants via the
364 C<Magpie::Constants> module so you do not have to try to remember what the
365 numeric codes are (this is similar to the way the C<Apache::Constants> module
366 works for HTTP return codes).
367  
368 use Magpie::Constants;
369  
370 sub myevent {
371 my $self = shift;
372 my $ctxt = shift;
373  
374 # do a little dance...
375  
376 return OK;
377 }
378  
379 The most common return codes and their effects on the application's behavior are as follows:
380  
381 =over
382  
383 =item C<< B<< OK >> >>
384  
385 Returning C<OK> from you event handler method signals Magpie that everything
386 went as expected during the method's run and that it is safe to continue.
387  
388 sub event_init {
389 my $self = shift;
390 my $ctxt = shift;
391  
392 # actual application behavior here
393  
394 # everything went well, continue on...
395 return OK;
396 }
397  
398 =item C<< B<< DECLINED >> >>
399  
400 Returning C<DECLINED> from your event handler method tells Magpie's internal
401 event queue to skip to the next application or output class in the pipeline.
402 Any other methods in the current application class that would usually be fired
403 based on the current state will be skipped.
404  
405 sub init {
406 my $self = shift;
407 my $ctxt = shift;
408  
409 unless ( defined $ctxt->{some_required_data} ) {
410 # we don't have the data we need to continue
411 $ctxt->{error_message} = "Insufficient data for init event";
412 return DECLINED;
413 }
414  
415 # otherwise continue on...
416 return OK;
417 }
418  
419 =item C<< B<< OUTPUT >> >>
420  
421 Where the C<DECLINED> return code signals Magpie to skip to the I<very next>
422 class in the pipeline, returning C<OUTPUT> from your event handler method
423 tells Magpie's internal event queue to skip to I<very last> class in the
424 application pipeline (which is presumed to be the Output class for the current
425 application).
426  
427 sub event_init {
428 my $self = shift;
429 my $ctxt = shift;
430  
431 unless ( my $user = $self->query->cookie('app_user') ) {
432 # like DECLINED above, but set a redirect
433 # header and skip directly to Output phase
434 $self->redirect('/login.xml');
435 return OUTPUT;
436 }
437  
438 # otherwise continue on...
439 return OK;
440 }
441  
442 =item C<< B<< DONE >> >>
443  
444 Returning C<DONE> from your event handler method stops the application
445 pipeline dead in its tracks. All subsequent classes that may be in the
446 pipeline are skippedIt is rarely used, given it
447 typically stops the application before any data is sent to the client, but it
448 can be useful for sending appropriate HTTP response codes.
449  
450 sub event_init {
451 my $self = shift;
452 my $ctxt = shift;
453  
454 unless ( -f $ctxt->{some_required_file} ) {
455 # we don't have the some crucial file needed to proceed
456 # so throw a 404 Not Found response while stopping the
457 # application
458 $self->response->status(404);
459 return DONE;
460 }
461  
462 # otherwise continue on...
463 return OK;
464 }
465  
466 =back
467  
468 =head1 References
469  
470 =over
471  
472 =item L<http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?finite+state+machine>
473  
474 FOLDOC definition of Finite State Machines.
475  
476 =back
477  
478 1;
479  
480 =head1 AUTHORS
481  
482 =over 4
483  
484 =item *
485  
486 Kip Hampton <kip.hampton@tamarou.com>
487  
488 =item *
489  
490 Chris Prather <chris.prather@tamarou.com>
491  
492 =back
493  
494 =head1 COPYRIGHT AND LICENSE
495  
496 This software is copyright (c) 2011 by Tamarou, LLC.
497  
498 This is free software; you can redistribute it and/or modify it under
499 the same terms as the Perl 5 programming language system itself.
500  
501 =cut
502  
503  
504 __END__
505  
« blib/lib/Magpie/Machine.pm ↑ Summary blib/lib/Magpie/Error.pm »