/
PoCoEvent.pm
66 lines (56 loc) · 1.5 KB
/
PoCoEvent.pm
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
package PoCoEvent;
# A component that accepts an event name to which return messages are
# posted. In this case, the component builds a postback for the
# calling session, which makes a more complex but satisfying test
# case.
#
# TODO - Refactor into a base class and subclasses. This is only a
# couple lines different from PoCoPostback.
use warnings;
use strict;
use POE;
sub new {
my $class = shift;
my $self = bless { }, $class;
my $result = 'aaaaaaaa';
POE::Session->create(
inline_states => {
_start => sub {
# Set an alias based on the object that owns us.
$_[HEAP]{alias} = "$self";
$_[KERNEL]->alias_set("$self");
},
shutdown => sub {
# Shutdown is triggered by the object DESTROY.
# Remove the alias, and gracefully exit when all pending
# timers are done.
$_[KERNEL]->alias_remove($_[HEAP]{alias});
},
request => sub {
# Handle a request. Feign some work.
my $event = $_[ARG0];
my $postback = $_[SENDER]->postback($event);
$_[KERNEL]->delay_add(
work_done => rand(3) => $postback => $result++
);
},
work_done => sub {
# When the work is done, post back a result.
my ($postback, $result) = @_[ARG0, ARG1];
$postback->($result);
},
},
);
return $self;
}
# Clean up the session on destruction.
sub DESTROY {
my $self = shift;
$poe_kernel->call("$self", "shutdown");
}
# Convenience method. Hide POE::Kernel->post.
sub request {
my ($self, $postback) = @_;
$poe_kernel->post("$self", "request", $postback);
}
1;