1POE::Session(3) User Contributed Perl Documentation POE::Session(3)
2
3
4
6 POE::Session - a generic event-driven task
7
9 use POE; # auto-includes POE::Kernel and POE::Session
10
11 POE::Session->create(
12 inline_states => {
13 _start => sub { $_[KERNEL]->yield("next") },
14 next => sub {
15 print "tick...\n";
16 $_[KERNEL]->delay(next => 1);
17 },
18 },
19 );
20
21 POE::Kernel->run();
22 exit;
23
24 POE::Session can also dispatch to object and class methods through
25 "object_states" and "package_states" callbacks.
26
28 POE::Session and its subclasses translate events from POE::Kernel's
29 generic dispatcher into the particular calling conventions suitable for
30 application code. In design pattern parlance, POE::Session classes are
31 adapters between POE::Kernel and application code.
32
33 The sessions that POE::Kernel manages are more like generic task
34 structures. Unfortunately these two disparate concepts have virtually
35 identical names.
36
37 A note on nomenclature
38 This documentation will refer to event handlers as "states" in certain
39 unavoidable situations. Sessions were originally meant to be event-
40 driven state machines, but their purposes evolved over time. Some of
41 the legacy vocabulary lives on in the API for backward compatibility,
42 however.
43
44 Confusingly, POE::NFA is a class for implementing actual event-driven
45 state machines. Its documentation uses "state" in the proper sense.
46
48 POE::Session has two main purposes. First, it maps event names to the
49 code that will handle them. Second, it maps a consistent event
50 dispatch interface to those handlers.
51
52 Consider the "SYNOPSIS" for example. A POE::Session instance is
53 created with two "inline_states", each mapping an event name ("_start"
54 and "next") to an inline subroutine. POE::Session ensures that
55 $_[KERNEL] and so on are meaningful within an event handler.
56
57 Event handlers may also be object or class methods, using
58 "object_states" and "package_states" respectively. The create() syntax
59 is different than for "inline_states", but the calling convention is
60 nearly identical.
61
62 Notice that the created POE::Session object has not been saved to a
63 variable. The new POE::Session object gives itself to POE::Kernel,
64 which then manages it and all the resources it uses.
65
66 It's possible to keep references to new POE::Session objects, but it's
67 not usually necessary. If an application is not careful about cleaning
68 up these references you will create circular references, which will
69 leak memory when POE::Kernel would normally destroy the POE::Session
70 object. It is recommended that you keep the session's "/ID" instead.
71
72 POE::Session's Calling Convention
73 The biggest syntactical hurdle most people have with POE is
74 POE::Session's unconventional calling convention. For example:
75
76 sub handle_event {
77 my ($kernel, $heap, $parameter) = @_[KERNEL, HEAP, ARG0];
78 ...;
79 }
80
81 Or the use of "/$_[KERNEL]", "/$_[HEAP]" and "/$_[ARG0]" inline, as is
82 done in most examples.
83
84 What's going on here is rather basic. Perl passes parameters into
85 subroutines or methods using the @_ array. "KERNEL", "HEAP", "ARG0"
86 and others are constants exported by POE::Session (which is included
87 for free when a program uses POE).
88
89 So "/$_[KERNEL]" is an event handler's KERNELth parameter. @_[HEAP,
90 ARG0] is a slice of @_ containing the HEAPth and ARG0th parameters.
91
92 While this looks odd, it's perfectly plain and legal Perl syntax. POE
93 uses it for a few reasons:
94
95 1. In the common case, passing parameters in @_ is faster than passing
96 hash or array references and then dereferencing them in the
97 handler.
98
99 2. Typos in hash-based parameter lists are either subtle run-time
100 errors or requires constant run-time checking. Constants are
101 either known at compile time, or are clear compile-time errors.
102
103 3. Referencing @_ offsets by constants allows parameters to move in
104 the future without breaking application code.
105
106 4. Most event handlers don't need all of @_. Slices allow handlers to
107 use only the parameters they're interested in.
108
109 POE::Session Parameters
110 Event handlers receive most of their run-time context in up to nine
111 callback parameters. POE::Kernel provides many of them.
112
113 $_[OBJECT]
114
115 $_[OBJECT] is $self for event handlers that are an object method. It
116 is the class (package) name for class-based event handlers. It is
117 undef for plain coderef callbacks, which have no special $self-ish
118 value.
119
120 "OBJECT" is always zero, since $_[0] is always $self or $class in
121 object and class methods. Coderef handlers are called with an "undef"
122 placeholder in $_[0] so that the other offsets remain valid.
123
124 It's often useful for method-based event handlers to call other methods
125 in the same object. $_[OBJECT] helps this happen.
126
127 sub ui_update_everything {
128 my $self = $_[OBJECT];
129 $self->update_menu();
130 $self->update_main_window();
131 $self->update_status_line();
132 }
133
134 You may also use method inheritance. Here we invoke
135 $self->a_method(@_). Since Perl's "<-">> operator unshifts $self onto
136 the beginning of @_, we must first shift a copy off to maintain POE's
137 parameter offsets:
138
139 sub a_method {
140 my $self = shift;
141 $self->SUPER::a_method( @_ );
142 # ... more work ...
143 }
144
145 $_[SESSION]
146
147 $_[SESSION] is a reference to the current session object. This lets
148 event handlers access their session's methods. Programs may also
149 compare $_[SESSION] to "/$_[SENDER]" to verify that intra-session
150 events did not come from other sessions.
151
152 $_[SESSION] may also be used as the destination for intra-session
153 "post()|POE::Kernel/post" and "call()|POE::Kernel/call".
154 "yield()|POE::Kernel/yield" is marginally more convenient and efficient
155 than "post($_[SESSION], ...)" however.
156
157 It is bad form to access another session directly. The recommended
158 approach is to manipulate a session through an event handler.
159
160 sub enable_trace {
161 my $previous_trace = $_[SESSION]->option( trace => 1 );
162 my $id = $_[SESSION]->ID;
163 if ($previous_trace) {
164 print "Session $id: dispatch trace is still on.\n";
165 }
166 else {
167 print "Session $id: dispatch trace has been enabled.\n";
168 }
169 }
170
171 $_[KERNEL]
172
173 The KERNELth parameter is always a reference to the application's
174 singleton POE::Kernel instance. It is most often used to call
175 POE::Kernel methods from event handlers.
176
177 # Set a 10-second timer.
178 $_[KERNEL]->delay( time_is_up => 10 );
179
180 $_[HEAP]
181
182 Every POE::Session object contains its own variable namespace known as
183 the session's "HEAP". It is modeled and named after process memory
184 heaps (not priority heaps). Heaps are by default anonymous hash
185 references, but they may be initialized in create() to be almost
186 anything. POE::Session itself never uses $_[HEAP], although some POE
187 components do.
188
189 Heaps do not overlap between sessions, although create()'s "heap"
190 parameter can be used to make this happen.
191
192 These two handlers time the lifespan of a session:
193
194 sub _start_handler {
195 $_[HEAP]{ts_start} = time();
196 }
197
198 sub _stop_handler {
199 my $time_elapsed = time() - $_[HEAP]{ts_start};
200 print "Session ", $_[SESSION]->ID, " elapsed seconds: $elapsed\n";
201 }
202
203 $_[STATE]
204
205 The STATEth handler parameter contains the name of the event being
206 dispatched in the current callback. This can be important since the
207 event and handler names may significantly differ. Also, a single
208 handler may be assigned to more than one event.
209
210 POE::Session->create(
211 inline_states => {
212 one => \&some_handler,
213 two => \&some_handler,
214 six => \&some_handler,
215 ten => \&some_handler,
216 _start => sub {
217 $_[KERNEL]->yield($_) for qw(one two six ten);
218 }
219 }
220 );
221
222 sub some_handler {
223 print(
224 "Session ", $_[SESSION]->ID,
225 ": some_handler() handled event $_[STATE]\n"
226 );
227 }
228
229 It should be noted however that having event names and handlers names
230 match will make your code easier to navigate.
231
232 $_[SENDER]
233
234 Events must come from somewhere. $_[SENDER] contains the currently
235 dispatched event's source.
236
237 $_[SENDER] is commonly used as a return address for responses. It may
238 also be compared against $_[KERNEL] to verify that timers and other
239 POE::Kernel-generated events were not spoofed.
240
241 This "echo_handler()" reponds to the sender with an "echo" event that
242 contains all the parameters it received. It avoids a feedback loop by
243 ensuring the sender session and event (STATE) are not identical to the
244 current ones.
245
246 sub echo_handler {
247 return if $_[SENDER] == $_[SESSION] and $_[STATE] eq "echo";
248 $_[KERNEL]->post( $_[SENDER], "echo", @_[ARG0..$#_] );
249 }
250
251 TODO - Document which events should have $_[SENDER] == $_[KERNEL].
252 Probably in POE::Kernel.
253
254 $_[CALLER_FILE], $_[CALLER_LINE] and $_[CALLER_STATE]
255
256 These parameters are a form of caller(), but they describe where the
257 currently dispatched event originated. CALLER_FILE and CALLER_LINE are
258 fairly plain. CALLER_STATE contains the name of the event that was
259 being handled when the event was created, or when the event watcher
260 that ultimately created the event was registered.
261
262 TODO - Rename SENDER_FILE, SENDER_LINE, SENDER_STATE?
263
264 @_[ARG0..ARG9] or @_[ARG0..$#_]
265
266 Parameters $_[ARG0] through the end of @_ contain parameters provided
267 by application code, event watchers, or higher-level libraries. These
268 parameters are guaranteed to be at the end of @_ so that @_[ARG0..$#_]
269 will always catch them all.
270
271 $#_ is the index of the last value in @_. Blame Perl if it looks odd.
272 It's merely the $#array syntax where the array name is an underscore.
273
274 Consider
275
276 $_[KERNEL]->yield( ev_whatever => qw( zero one two three ) );
277
278 The handler for ev_whatever will be called with "zero" in $_[ARG0],
279 "one" in $_[ARG1], and so on. @_[ARG0..$#_] will contain all four
280 words.
281
282 sub ev_whatever {
283 $_[OBJECT]->whatever( @_[ARG0..$#_] );
284 }
285
286 Using POE::Session With Objects
287 One session may handle events across many objects. Or looking at it
288 the other way, multiple objects can be combined into one session. And
289 what the heck---go ahead and mix in some inline code as well.
290
291 POE::Session->create(
292 object_states => [
293 $object_1 => { event_1a => "method_1a" },
294 $object_2 => { event_2a => "method_2a" },
295 ],
296 inline_states => {
297 event_3 => \&piece_of_code,
298 },
299 );
300
301 However only one handler may be assigned to a given event name.
302 Duplicates will overwrite earlier ones.
303
304 event_1a is handled by calling "$object_1->method_1a(...)". $_[OBJECT]
305 is $object_1 in this case. $_[HEAP] belongs to the session, which
306 means anything stored there will be available to any other event
307 handler regardless of the object.
308
309 event_2a is handled by calling "$object_2->method_2a(...)". In this
310 case "/$_[OBJECT]" is $object_2. $_[HEAP] is the same anonymous
311 hashref that was passed to the event_1a handler, though. The methods
312 are resolved when the event is handled (late-binding).
313
314 event_3 is handled by calling "piece_of_code(...)". $_[OBJECT] is
315 "undef" here because there's no object. And once again, $_[HEAP] is
316 the same shared hashref that the handlers for event_1a and event_2a
317 saw.
318
319 Interestingly, there's no technical reason that a single object can't
320 handle events from more than one session:
321
322 for (1..2) {
323 POE::Session->create(
324 object_states => [
325 $object_4 => { event_4 => "method_4" },
326 ]
327 );
328 }
329
330 Now "$object_4->method_4(...)" may be called to handle events from one
331 of two sessions. In both cases, $_[OBJECT] will be $object_4, but
332 $_[HEAP] will hold data for a particular session.
333
334 The same goes for inline states. One subroutine may handle events from
335 many sessions. $_[SESSION] and $_[HEAP] can be used within the handler
336 to easily access the context of the session in which the event is being
337 handled.
338
340 POE::Session has just a few public methods.
341
342 create LOTS_OF_STUFF
343 "create()" starts a new session running. It returns a new POE::Session
344 object upon success, but most applications won't need to save it.
345
346 "create()" invokes the newly started session's _start event handler
347 before returning.
348
349 "create()" also passes the new POE::Session object to "POE::Kernel".
350 POE's kernel holds onto the object in order to dispatch events to it.
351 POE::Kernel will release the object when it detects the object has
352 become moribund. This should cause Perl to destroy the object if
353 application code has not saved a copy of it.
354
355 "create()" accepts several named parameters, most of which are
356 optional. Note however that the parameters are not part of a hashref.
357
358 TODO - Is it time to bring new() back as a synonym for create()? TODO
359 PG - NO! IMHO ->new implies simply creating the object, and TODO that
360 you have to hold onto the object. ->create implies other actions TODO
361 are happening, and that you don't want to hold on to it.
362
363 TODO - Provide forward-compatible "handler" options and methods as
364 synonyms for the "state" versions currently supported? TODO PG - No,
365 that's for 1.01
366
367 TODO - Add a "class_handlers" as a synonym for "package_handlers"?
368 TODO PG - Maybe. However, to many synonyms can be a pain for an API.
369
370 TODO - The above TODOs may be summarized: "deprecate old language"?
371 TODO PG - Oh, you are thinking of deprecating the old language...
372 erm... no?
373
374 TODO PG - I notice these =head3 are in alphabetical order. I think
375 TODO all the *_states options should be together. Followed by heap,
376 args, TODO options
377
378 args => ARRAYREF
379
380 The "args" parameter accepts a reference to a list of parameters that
381 will be passed to the session's _start event handler in @_ positions
382 "ARG0" through $#_ (the end of @_).
383
384 This example would print "arg0 arg1 etc.":
385
386 POE::Session->create(
387 inline_states => {
388 _start => sub {
389 print "Session started with arguments: @_[ARG0..$#_]\n";
390 },
391 },
392 args => [ 'arg0', 'arg1', 'etc.' ],
393 );
394
395 heap => ANYTHING
396
397 The "heap" parameter allows a session's heap to be initialized
398 differently at instantiation time. Heaps are usually anonymous
399 hashrefs, but "heap" may set them to be array references or even
400 objects.
401
402 This example prints "tree":
403
404 POE::Session->create(
405 inline_states => {
406 _start => sub {
407 print "Slot 0 = $_[HEAP][0]\n";
408 },
409 },
410 heap => [ 'tree', 'bear' ],
411 );
412
413 Be careful when initializing the heap to be something that doesn't
414 behave like a hashref. Some libraries assume hashref heap semantics,
415 and they will fail if the heap doesn't work that way.
416
417 inline_states => HASHREF
418
419 "inline_states" maps events names to the subroutines that will handle
420 them. Its value is a hashref that maps event names to the coderefs of
421 their corresponding handlers:
422
423 POE::Session->create(
424 inline_states => {
425 _start => sub {
426 print "arg0=$_[ARG0], arg1=$_[ARG1], etc.=$_[ARG2]\n";
427 },
428 _stop => \&stop_handler,
429 },
430 args => [qw( arg0 arg1 etc. )],
431 );
432
433 The term "inline" comes from the fact that coderefs can be inlined
434 anonymous subroutines.
435
436 Be very careful with closures, however. "Beware circular references".
437
438 object_states => ARRAYREF
439
440 "object_states" associates one or more objects to a session and maps
441 event names to the object methods that will handle them. It's value is
442 an "ARRAYREF"; "HASHREFs" would stringify the objects, ruining them for
443 method invocation.
444
445 Here _start is handled by "$object->_session_start()" and _stop
446 triggers "$object->_session_stop()":
447
448 POE::Session->create(
449 object_states => [
450 $object => {
451 _start => '_session_start',
452 _stop => '_session_stop',
453 }
454 ]
455 );
456
457 POE::Session also supports a short form where the event and method
458 names are identical. Here _start invokes $object->_start(), and _stop
459 triggers $object->_stop():
460
461 POE::Session->create(
462 object_states => [
463 $object => [ '_start', '_stop' ],
464 ]
465 );
466
467 Methods are verified when the session is created, but also resolved
468 when the handler is called (late binding). Most of the time, a method
469 won't change. But in some circumstance, such as dynamic inheritance, a
470 method could resolve to a different subroutine.
471
472 options => HASHREF
473
474 POE::Session sessions support a small number of options, which may be
475 initially set with the "option" constructor parameter and changed at
476 run time with the "option()|/option" mehtod.
477
478 "option" takes a hashref with option => value pairs:
479
480 POE::Session->create(
481 ... set up handlers ...,
482 options => { trace => 1, debug => 1 },
483 );
484
485 This is equivalent to the previous example:
486
487 POE::Session->create(
488 ... set up handlers ...,
489 )->option( trace => 1, debug => 1 );
490
491 The supported options and values are documented with the
492 "option()|/option" method.
493
494 package_states => ARRAYREF
495
496 "package_states" associates one or more classes to a session and maps
497 event names to the class methods that will handle them. Its function
498 is analogous to "object_states", but package names are specified rather
499 than objects.
500
501 In fact, the following documentation is a copy of the "object_states"
502 description with some word substitutions.
503
504 The value for "package_states" is an ARRAYREF to be consistent with
505 "object_states", even though class names (also known as package names)
506 are already strings, so it's not necessary to avoid stringifying them.
507
508 Here _start is handled by "$class_name->_session_start()" and _stop
509 triggers "$class_name->_session_stop()":
510
511 POE::Session->create(
512 package_states => [
513 $class_name => {
514 _start => '_session_start',
515 _stop => '_session_stop',
516 }
517 ]
518 );
519
520 POE::Session also supports a short form where the event and method
521 names are identical. Here _start invokes "$class_name->_start()", and
522 _stop triggers "$class_name->_stop()":
523
524 POE::Session->create(
525 package_states => [
526 $class_name => [ '_start', '_stop' ],
527 ]
528 );
529
530 ID
531 "ID()" returns the session instance's unique identifier. This is an
532 integer that starts at 1 and counts up forever, or until the number
533 wraps around.
534
535 It's theoretically possible that a session ID will not be unique, but
536 this requires at least 4.29 billion sessions to be created within a
537 program's lifespan. POE guarantees that no two sessions will have the
538 same ID at the same time, however; your computer doesn't have enough
539 memory to store 4.29 billion session objects.
540
541 A session's ID is unique within a running process, but multiple
542 processes are likely to have the same session IDs. If a global ID is
543 required, it will need to include both "$_[KERNEL]->ID" and
544 "$_[SESSION]->ID".
545
546 option OPTION_NAME [, OPTION_VALUE [, OPTION_NAME, OPTION_VALUE]... ]
547 "option()" sets and/or retrieves the values of various session options.
548 The options in question are implemented by POE::Session and do not have
549 any special meaning anywhere else.
550
551 It may be called with a single OPTION_NAME to retrieve the value of
552 that option.
553
554 my $trace_value = $_[SESSION]->option('trace');
555
556 "option()" sets an option's value when called with a single
557 OPTION_NAME, OPTION_VALUE pair. In this case, "option()" returns the
558 option's previous value.
559
560 my $previous_trace = $_[SESSION]->option(trace => 1);
561
562 "option()" may also be used to set the values of multiple options at
563 once. In this case, "option()" returns all the specified options'
564 previous values in an anonymous hashref:
565
566 my $previous_values = $_[SESSION]->option(
567 trace => 1,
568 debug => 1,
569 );
570
571 print "Previous option values:\n";
572 while (my ($option, $old_value) = each %$previous_values) {
573 print " $option = $old_value\n";
574 }
575
576 POE::Session currently supports three options:
577
578 The "debug" option.
579
580 The "debug" option is intended to enable additional warnings when
581 strange things are afoot within POE::Session. At this time, there is
582 only one additional warning:
583
584 ยท Redefining an event handler does not usually cause a warning, but
585 it will when the "debug" option is set.
586
587 The "default" option.
588
589 Enabling the "default" option causes unknown events to become warnings,
590 if there is no _default handler to catch them.
591
592 The class-level "POE::Session::ASSERT_STATES" flag is implemented by
593 enabling the "default" option on all new sessions.
594
595 The "trace" option.
596
597 Turn on the "trace" option to dump a log of all the events dispatched
598 to a particular session. This is a session-specific trace option that
599 allows individual sessions to be debugged.
600
601 Session-level tracing also indicates when events are redirected to
602 _default. This can be used to discover event naming errors.
603
604 User-defined options.
605
606 "option()" does not verify whether OPTION_NAMEs are known, so
607 "option()" may be used to store and retrieve user-defined information.
608
609 Choose option names with caution. There is no established convention
610 to avoid namespace collisions between user-defined options and future
611 internal options.
612
613 postback EVENT_NAME, EVENT_PARAMETERS
614 "postback()" manufactures callbacks that post POE events. It returns
615 an anonymous code reference that will post EVENT_NAME to the target
616 session, with optional EVENT_PARAMETERS in an array reference in ARG0.
617 Parameters passed to the callback will be sent in an array reference in
618 ARG1.
619
620 In other words, ARG0 allows the postback's creator to pass context
621 through the postback. ARG1 allows the caller to return information.
622
623 This example creates a coderef that when called posts "ok_button" to
624 $some_session with ARG0 containing "[ 8, 6, 7 ]".
625
626 my $postback = $some_session->postback( "ok_button", 8, 6, 7 );
627
628 Here's an example event handler for "ok_button".
629
630 sub handle_ok_button {
631 my ($creation_args, $called_args) = @_[ARG0, ARG1];
632 print "Postback created with (@$creation_args).\n";
633 print "Postback called with (@$called_args).\n";
634 }
635
636 Calling $postback->(5, 3, 0, 9) would perform the equivalent of...
637
638 $poe_kernel->post(
639 $some_session, "ok_button",
640 [ 8, 6, 7 ],
641 [ 5, 3, 0, 9 ]
642 );
643
644 This would be displayed when "ok_button" was dispatched to
645 handle_ok_button():
646
647 Postback created with (8 6 7).
648 Postback called with (5 3 0 9).
649
650 Postbacks hold references to their target sessions. Therefore sessions
651 with outstanding postbacks will remain active. Under every event loop
652 except Tk, postbacks are blessed so that DESTROY may be called when
653 their users are done. This triggers a decrement on their reference
654 counts, allowing sessions to stop.
655
656 Postbacks have one method, weaken(), which may be used to reduce their
657 reference counts upon demand. weaken() returns the postback, so you
658 can do:
659
660 my $postback = $session->postback("foo")->weaken();
661
662 Postbacks were created as a thin adapter between callback libraries and
663 POE. The problem at hand was how to turn callbacks from the Tk
664 graphical toolkit's widgets into POE events without subclassing several
665 Tk classes. The solution was to provide Tk with plain old callbacks
666 that posted POE events.
667
668 Since "postback()" and "callback()" are Session methods, they may be
669 called on $_[SESSION] or $_[SENDER], depending on particular needs.
670 There are usually better ways to interact between sessions than abusing
671 postbacks, however.
672
673 Here's a brief example of attaching a Gtk2 button to a POE event
674 handler:
675
676 my $btn = Gtk2::Button->new("Clear");
677 $btn->signal_connect( "clicked", $_[SESSION]->postback("ev_clear") );
678
679 Points to remember: The session will remain alive as long as $btn
680 exists and holds a copy of $_[SESSION]'s postback. Any parameters
681 passed by the Gtk2 button will be in ARG1.
682
683 callback EVENT_NAME, EVENT_PARAMETERS
684 callback() manufactures callbacks that use "$poe_kernel->call()" to
685 deliver POE events rather than "$poe_kernel->post()". It is identical
686 to "postback()" in every other respect.
687
688 callback() was created to avoid race conditions that arise when
689 external libraries assume callbacks will execute synchronously.
690 File::Find is an obvious (but not necessarily appropriate) example. It
691 provides a lot of information in local variables that stop being valid
692 after the callback. The information would be unavailable by the time a
693 post()ed event was dispatched.
694
695 get_heap
696 "get_heap()" returns a reference to a session's heap. This is the same
697 value as $_[HEAP] for the target session. "get_heap()" is intended to
698 be used with $poe_kernel and POE::Kernel's "get_active_session()" so
699 that libraries do not need these three common values explicitly passed
700 to them.
701
702 That is, it prevents the need for:
703
704 sub some_helper_function {
705 my ($kernel, $session, $heap, @specific_parameters) = @_;
706 ...;
707 }
708
709 Rather, helper functions may use:
710
711 use POE::Kernel; # exports $poe_kernel
712 sub some_helper_function {
713 my (@specific_parameters) = @_;
714 my $session = $poe_kernel->get_active_session();
715 my $heap = $session->get_heap();
716 }
717
718 This isn't very convenient for people writing libraries, but it makes
719 the libraries much more convenient to use.
720
721 Using "get_heap()" to break another session's encapsulation is strongly
722 discouraged.
723
724 instantiate CREATE_PARAMETERS
725 "instantiate()" creates and returns an empty POE::Session object. It
726 is called with the CREATE_PARAMETERS in a hash reference just before
727 "create()" processes them. Modifications to the CREATE_PARAMETERS will
728 affect how "create()" initializes the new session.
729
730 Subclasses may override "instantiate()" to alter the underlying
731 session's structure. They may extend "instantiate()" to add new
732 parameters to "create()".
733
734 Any parameters not recognized by "create()" must be removed from the
735 CREATE_PARAMETERS before "instantiate()" returns. "create()" will
736 croak if it discovers unknown parameters.
737
738 Be sure to return $self from instantiate.
739
740 sub instantiate {
741 my ($class, $create_params) = @_;
742
743 # Have the base class instantiate the new session.
744 my $self = $class->SUPER::instantiate($create_parameters);
745
746 # Extend the parameters recognized by create().
747 my $new_option = delete $create_parameters->{new_option};
748 if (defined $new_option) {
749 # ... customize $self here ...
750 }
751
752 return $self;
753 }
754
755 try_alloc START_ARGS
756 "try_alloc()" calls POE::Kernel's "session_alloc()" to allocate a
757 session structure and begin managing the session within POE's kernel.
758 It is called at the end of POE::Session's "create()". It returns
759 $self.
760
761 It is a subclassing hook for late session customization prior to
762 "create()" returning. It may also affect the contents of @_[ARG0..$#_]
763 that are passed to the session's _start handler.
764
765 sub try_alloc {
766 my ($self, @start_args) = @_;
767
768 # Perform late initialization.
769 # ...
770
771 # Give $self to POE::Kernel.
772 return $self->SUPER::try_alloc(@args);
773 }
774
776 Please do not define new events that begin with a leading underscore.
777 POE claims /^_/ events as its own.
778
779 POE::Session only generates one event, _default. All other internal
780 POE events are generated by (and documented in) POE::Kernel.
781
782 _default
783 _default is the "AUTOLOAD" of event handlers. If POE::Session can't
784 find a handler at dispatch time, it attempts to redirect the event to
785 _default's handler instead.
786
787 If there's no _default handler, POE::Session will silently drop the
788 event unless the "default" option is set.
789
790 To preserve the original information, the original event is slightly
791 changed before being redirected to the _default handler: The original
792 event parameters are moved to an array reference in ARG1, and the
793 original event name is passed to _default in ARG0.
794
795 sub handle_default {
796 my ($event, $args) = @_[ARG0, ARG1];
797 print(
798 "Session ", $_[SESSION]->ID,
799 " caught unhandled event $event with (@$args).\n"
800 );
801 }
802
803 _default is quite flexible. It may be used for debugging, or to handle
804 dynamically generated event names without pre-defining their handlers.
805 In the latter sense, _default performs analogously to Perl's
806 "AUTOLOAD".
807
808 _default may also be used as the default or "otherwise" clause of a
809 switch statement. Consider an input handler that throws events based
810 on a command name:
811
812 sub parse_command {
813 my ($command, @parameters) = split /\s+/, $_[ARG0];
814 $_[KERNEL]->post( "cmd_$command", @parameters );
815 }
816
817 A _default handler may be used to emit errors for unknown commands:
818
819 sub handle_default {
820 my $event = $_[ARG0];
821 return unless $event =~ /^cmd_(\S+)/;
822 warn "Unknown command: $1\n";
823 }
824
825 The _default behavior is implemented in POE::Session, so it may be
826 different for other session types.
827
828 POE::Session's Debugging Features
829 POE::Session contains one debugging assertion, for now.
830
831 ASSERT_STATES
832
833 Setting ASSERT_STATES to true causes every Session to warn when they
834 are asked to handle unknown events. Session.pm implements the guts of
835 ASSERT_STATES by defaulting the "default" option to true instead of
836 false. See the option() method earlier in this document for details
837 about the "default" option.
838
839 TODO - It's not much of an assertion if it only warns.
840
842 POE::Kernel.
843
844 The SEE ALSO section in POE contains a table of contents covering the
845 entire POE distribution.
846
848 There is a chance that session IDs may collide after Perl's integer
849 value wraps. This can occur after as few as 4.29 billion sessions.
850
851 Beware circular references
852 As you're probably aware, a circular reference is when a variable is
853 part of a reference chain that eventually refers back to itself. Perl
854 will not reclaim the memory involved in such a reference chain until
855 the chain is manually broken.
856
857 Here a POE::Session is created that refers to itself via an external
858 scalar. The event handlers import $session via closures which are in
859 turn stored within $session. Even if this session stops, the circular
860 references will remain.
861
862 my $session;
863 $session = POE::Session->create(
864 inline_states => {
865 _start => sub {
866 $_[HEAP]->{todo} = [ qw( step1 step2 step2a ) ],
867 $_[KERNEL]->post( $session, 'next' );
868 },
869 next => sub {
870 my $next = shift @{ $_[HEAP]->{todo} };
871 return unless $next;
872 $_[KERNEL]->post( $session, $next );
873 }
874 # ....
875 }
876 );
877
878 Reduced to its essence:
879
880 my %event_handlers;
881 $event_handler{_start} = sub { \%event_handlers };
882
883 Note also that a anonymous sub creates a closure on all lexical
884 variables in the scope it was defined in, even if it doesn't reference
885 them. $session is still being held in a circular reference here:
886
887 my $self = $package->new;
888 my $session;
889 $session = POE::Session->create(
890 inline_state => {
891 _start => sub { $self->_start( @_[ARG0..$#_] ) }
892 }
893 );
894
895 To avoid this, a session may set an alias for itself. Other parts of
896 the program may then refer to it by alias. In this case, one needn't
897 keep track of the session themselves (POE::Kernel will do it anyway).
898
899 POE::Session->create(
900 inline_states => {
901 _start => sub {
902 $_[HEAP]->{todo} = [ qw( step1 step2 step2a ) ],
903 $_[KERNEL]->alias_set('step_doer');
904 $_[KERNEL]->post( 'step_doer', 'next' );
905 },
906 next => sub {
907 my $next = shift @{ $_[HEAP]->{todo} };
908 return unless $next;
909 $_[KERNEL]->post( 'step_doer', $next );
910 }
911 # ....
912 }
913 );
914
915 Aliases aren't even needed in the previous example because the session
916 refers to itself. One could instead use POE::Kernel's yield() method
917 to post the event back to the current session:
918
919 next => sub {
920 my $next = shift @{ $_[HEAP]->{todo} };
921 return unless $next;
922 $_[KERNEL]->yield( $next );
923 }
924
925 Or the $_[SESSION] parameter passed to every event handler, but yield()
926 is more efficient.
927
928 next => sub {
929 my $next = shift @{ $_[HEAP]->{todo} };
930 return unless $next;
931 $_[KERNEL]->post( $_[SESSION], $next );
932 }
933
934 Along the same lines as $_[SESSION], a session can respond back to the
935 sender of an event by posting to $_[SENDER]. This is great for
936 responding to requests.
937
938 If a program must hold onto some kind of dynamic session reference,
939 it's recommended to use the session's numeric ID rather than the object
940 itself. A session ID may be converted back into its object, but post()
941 accepts session IDs as well as objects and aliases:
942
943 my $session_id;
944 $session_id = POE::Session->create(
945 inline_states => {
946 _start => sub {
947 $_[HEAP]->{todo} = [ qw( step1 step2 step2a ) ],
948 $_[KERNEL]->post( $session_id, 'next' );
949 },
950 # ....
951 }
952 )->ID;
953
955 Please see POE for more information about authors and contributors.
956
957
958
959perl v5.12.1 2010-04-03 POE::Session(3)