Advertisement
Guest User

Zend Multi Client

a guest
Jan 5th, 2011
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.08 KB | None | 0 0
  1. <?php
  2. /**
  3.  * клиент Используемый для работы с http (MULTI curl);
  4.  * @author mapron
  5.  * @see Zend_Http_Client
  6.  * @see App_Http_ClientAdapter_Multi
  7.  */
  8. class App_Http_MultiClient extends Zend_Http_Client
  9. {
  10.     protected $requests = array();
  11.    
  12.     protected $fieldsCopy = array( 'headers', 'method', 'paramsGet', 'paramsPost', 'enctype', 'raw_post_data', 'auth',
  13.     'files' ); 
  14.    
  15.     /**
  16.      * Данная функция завершает текущий запрос и помещает его в очередь.
  17.      * @param unknown_type $id
  18.      */
  19.     public function finishRequest($id = null)
  20.     {
  21.         $request = array();    
  22.         foreach ($this->fieldsCopy as $field) {
  23.             $request[$field] = $this->$field;
  24.         }
  25.         foreach (array('uri', 'cookiejar') as $field) {
  26.             if (!is_null($this->$field)) {
  27.                 $request[$field] = clone $this->$field;
  28.             }
  29.         }
  30.        
  31.         $config = $this->config;
  32.         unset($config['adapter']); // это, в принципе, не критично, ибо объект мы создаем вручную в request().
  33.         // Сделано для совместимости с возомжными изменениями в Zend.
  34.        
  35.         $request['_config'] = $this->config;
  36.         if (is_null($id)){ // можно не передавать $id, будет просто индексированный массив.
  37.             $this->requests[] = $request;
  38.         } else {
  39.             $this->requests[$id] = $request;
  40.         }
  41.     }
  42.    
  43.     /**
  44.      * Метод, который обрабатывает все ранее сделанные запросы
  45.      * @see Zend_Http_Client::request()
  46.      */
  47.     public function request()
  48.     {
  49.         if (empty($this->requests)) {
  50.             throw new Zend_Http_Client_Exception('Request queue is empty.');
  51.         }
  52.         $this->redirectCounter = 0;
  53.         $response = null;
  54.        
  55.         // Да, выглядит как грязный хак, но так оно и есть. Данный класс просто не поддерживает другие адаптеры.
  56.         $this->adapter = new App_Http_ClientAdapter_Multi();         
  57.        
  58.         $requests = array();
  59.         $this->last_request = array();
  60.        
  61.         foreach ($this->requests as $id => &$requestPure){
  62.             //  Здесь и ниже немного измененная копия первоначального кода.
  63.            
  64.             // Копируем параметры для запроса.
  65.             foreach ($this->fieldsCopy as $field) $this->$field = $requestPure[$field];
  66.            
  67.             // обрабатываем URI, приводя к стандартному виду.
  68.             $uri = $requestPure['uri'];
  69.             if (! empty($requestPure['paramsGet'])){
  70.                 $query = $uri->getQuery();
  71.                 if (! empty($query)) {
  72.                     $query .= '&';
  73.                 }
  74.                 $query .= http_build_query($requestPure['paramsGet'], null, '&');
  75.                 $requestPure['paramsGet'] = array();
  76.                 $uri->setQuery($query);
  77.             }
  78.            
  79.             // тело запроса
  80.             $body = $this->_prepareBody();
  81.             if (! isset($this->headers['host'])) {
  82.                 $this->headers['host'] = array('Host', $uri->getHost());           
  83.             }
  84.             $headers = $this->_prepareHeaders();
  85.            
  86.             // записываем по кусочкам в массив
  87.             $request = array();
  88.             $request['host'] = $uri->getHost();
  89.             $request['port'] = $uri->getPort();
  90.             $request['scheme'] = ($uri->getScheme() == 'https' ? true : false);
  91.             $request['method'] = $this->method;
  92.             $request['uri'] = $uri;
  93.             $request['httpversion'] = $this->config['httpversion'];
  94.             $request['headers'] = $headers;
  95.             $request['body'] = $body;
  96.             $request['_config'] = $requestPure['_config'];
  97.             $requests[$id] = $request;
  98.         }
  99.        
  100.         // запоминаем запросы, вдруг понадобятся в отладке!
  101.         $this->last_request = $requests;
  102.        
  103.         // выполняем мульти-запрос.
  104.         $this->adapter->execute($requests);
  105.        
  106.         // метод read() на самом деле просто извлекает уже сохраненный результат.
  107.         $responses = $this->adapter->read();
  108.        
  109.         if (! $responses) {
  110.             throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
  111.         }
  112.      
  113.         // преобразуем ответы в удобный Zend_Http_Response для дальнейшей работы.
  114.         foreach ($responses as &$response){        
  115.             $response = Zend_Http_Response::fromString($response);     
  116.         }
  117.        
  118.         if ($this->config['storeresponse']) {
  119.             $this->last_response = $response;
  120.         }
  121.        
  122.         return $responses;
  123.     }
  124.  
  125. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement