Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 80 lines (62 sloc) 1.667 kb
8a4f21a @rcaputo Refactor the HTTP client example so that the client can be reused.
authored
1 package HttpClient;
2
3 use Moose;
4 extends 'Reflex::Base';
5
6 use POE::Component::Client::HTTP;
7 use Reflex::POE::Event;
8 use HttpResponseEvent;
9
10 has alias => (
11 is => 'ro',
12 isa => 'Str',
13 default => 'user-agent',
14 );
15
16 sub BUILD {
17 my ($self) = @_;
18
19 # Start an HTTP user-agent when the object is created.
20 #
21 # A more complete example would expose all of PoCo::Client::HTTP's
22 # configuration options as attributes.
23
24 POE::Component::Client::HTTP->spawn(Alias => $self->alias());
25 }
26
27 sub DESTRUCT {
28 my ($self) = @_;
29
30 # Shut down POE::Component::Client::HTTP when this object is
31 # destroyed.
32
33 POE::Kernel->post(ua => $self->alias());
34 }
35
36 sub request {
37 # Make a request.
38
39 my ($self, $http_request) = @_;
40
41 # There is no guarantee that the caller of request() is running in
42 # the same POE session as this HttpClient object.
43 #
44 # Reflex::Base's run_within_session() method makes sure that the
45 # right session is active when interacting with POE code. This
46 # ensures that POE-based responses are properly routed.
47
48 # The Reflex::POE::Event object created here is an event for POE's
49 # purpose, but it includes Reflex magic to route responses back to
50 # the correct Reflex object.
51
52 $self->run_within_session(
53 sub {
54 POE::Kernel->post(
55 $self->alias(),
56 'request',
57 Reflex::POE::Event->new(
58 object => $self,
59 method => 'internal_http_response',
60 ),
61 $http_request,
62 );
63 }
64 );
65 }
66
67 sub internal_http_response {
68 my ($self, $args) = @_;
69
70 my ($request, $response) = @{ $args->{response} };
71 $self->emit(
72 -type => 'HttpResponseEvent',
73 -name => 'response',
74 request => $request->[0],
75 response => $response->[0],
76 );
77 }
78
79 1;
Something went wrong with that request. Please try again.