flush docs
[mdref/mdref-http] / http / Client / Curl / User / : Examples.md
1 # http\Client\Curl\User Examples
2
3 ## Example using the [pecl/ev](http://pecl.php.net/ev) loop:
4
5 <?php
6
7 class UserHandler implements http\Client\Curl\User
8 {
9 private $client;
10 private $run;
11 private $ios = [];
12 private $timeout;
13
14
15 function __construct(http\Client $client) {
16 $this->client = $client;
17 }
18
19 function init(callable $run) {
20 $this->run = $run;
21 }
22
23 function timer(int $timeout_ms) {
24 echo "T";
25 if (isset($this->timeout)) {
26 $this->timeout->set($timeout_ms/1000, 0);
27 $this->timeout->start();
28 } else {
29 $this->timeout = new EvTimer($timeout_ms/1000, 0, function() {
30 if (!call_user_func($this->run, $this->client)) {
31 if ($this->timeout) {
32 $this->timeout->stop();
33 $this->timeout = null;
34 }
35 }
36 });
37 }
38 }
39
40 function socket($socket, int $action) {
41 echo "S";
42
43 switch ($action) {
44 case self::POLL_NONE:
45 break;
46 case self::POLL_REMOVE:
47 if (isset($this->ios[(int) $socket])) {
48 echo "U";
49 $this->ios[(int) $socket]->stop();
50 unset($this->ios[(int) $socket]);
51 }
52 break;
53
54 default:
55 $ev = 0;
56 if ($action & self::POLL_IN) {
57 $ev |= Ev::READ;
58 }
59 if ($action & self::POLL_OUT) {
60 $ev |= Ev::WRITE;
61 }
62 if (isset($this->ios[(int) $socket])) {
63 $this->ios[(int) $socket]->set($socket, $ev);
64 } else {
65 $this->ios[(int) $socket] = new EvIo($socket, $ev, function($watcher, $events) use($socket) {
66 $action = 0;
67 if ($events & Ev::READ) {
68 $action |= self::POLL_IN;
69 }
70 if ($events & Ev::WRITE) {
71 $action |= self::POLL_OUT;
72 }
73 if (!call_user_func($this->run, $this->client, $socket, $action)) {
74 if ($this->timeout) {
75 $this->timeout->stop();
76 $this->timeout = null;
77 }
78 }
79 });
80 }
81 break;
82 }
83 }
84
85 function once() {
86 throw new BadMethodCallException("this example uses Ev::run()");
87 }
88
89 function wait(int $timeout_ms = null) {
90 throw new BadMethodCallException("this example uses Ev::run()");
91 }
92
93 function send() {
94 throw new BadMethodCallException("this example uses Ev::run()");
95 }
96 }
97
98 $client = new http\Client;
99 $client->configure([
100 "use_eventloop" => new UserHandler($client)
101 ]);
102 $client->enqueue(new http\Client\Request("GET", "http://example.com/"), function($r) {
103 var_dump($r->getResponseCode());
104 });
105
106 Ev::run();
107
108 ?>
109
110 ### Yields:
111
112 TTTTTTTTSTSTSUint(200)