Observing Requests

Both HTTP_Request and HTTP_Client have attach and detach methods for adding and removing instances of HTTP_Request_Listener. This class implements the observer design pattern and serves to intercept events that occur during the process of transmitting a request and receiving a response. To create an observer, first create a class that extends HTTP_Request_Listener as shown below.

<?php
class Custom_Request_Listener extends HTTP_Request_Listener {
function Custom_Request_Listener()
{
$this->HTTP_Request_Listener();
}
function update(&$subject, $event, $data = null)
{
switch ($event) {

// Request events
case 'connect': // handle the 'connect' event
case 'sentRequest': // ...
case 'disconnect': // ...

// Response events case 'gotHeaders': // ...
case 'tick': // ...
case 'gztick': // ...
case 'gotBody': // ...

// Client events case 'request': // ...
case 'httpSuccess': // ...
case 'httpRedirect': // ... case 'httpError': // ...
default:
PEAR::raiseError('Unhandled error: ' . $event);
}
}
}
?>
  • Declare a constructor that calls the parent constructor and performs any needed custom logic.
  • Declare the update method with the signature shown. $subject is the request or client instance to which the listener is attached. $event is a string containing one of the events shown in the switch statement.
  • $data is data specific to events related to reception of the server response.
  • Request and response events occur within HTTP_Request instances. Client events occur within HTTP_Client instances.
  • Note that not all events need to be handled, only those with which you are concerned.

The attach method in HTTP_Request takes a single parameter, a listener instance. The equivalent method in HTTP_Client takes two parameters, a required listener instance and an optional boolean flag. When the latter is false (which it is by default), attached listeners will not be propagated to requests created within the client instance. That is, a listener added will not be notified of request and response events, only client events. To have an added listener receive all events, explicitly specify the $propagate parameter to be true when calling attach. 


© PEAR::HTTP_Client — Web Scraping

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (01.09.2014)
Views: 359 | Rating: 0.0/0
Total comments: 0
avatar