[ Index ]

PHP Cross Reference of Phabricator

title

Body

[close]

/externals/httpful/src/Httpful/Handlers/ -> README.md (source)

   1  # Handlers
   2  
   3  Handlers are simple classes that are used to parse response bodies and serialize request payloads.  All Handlers must extend the `MimeHandlerAdapter` class and implement two methods: `serialize($payload)` and `parse($response)`.  Let's build a very basic Handler to register for the `text/csv` mime type.
   4  
   5      <?php
   6  
   7      class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter
   8      {
   9          /**
  10           * Takes a response body, and turns it into 
  11           * a two dimensional array.
  12           *
  13           * @param string $body
  14           * @return mixed
  15           */
  16          public function parse($body)
  17          {
  18              return str_getcsv($body);
  19          }
  20      
  21          /**
  22           * Takes a two dimensional array and turns it
  23           * into a serialized string to include as the 
  24           * body of a request
  25           *
  26           * @param mixed $payload
  27           * @return string
  28           */
  29          public function serialize($payload)
  30          {
  31              $serialized = '';
  32              foreach ($payload as $line) {
  33                  $serialized .= '"' . implode('","', $line) . '"' . "\n";
  34              }
  35              return $serialized;
  36          }
  37      }
  38  
  39  
  40  Finally, you must register this handler for a particular mime type.
  41  
  42      Httpful::register('text/csv', new SimpleCsvHandler());
  43  
  44  After this registering the handler in your source code, by default, any responses with a mime type of text/csv should be parsed by this handler.


Generated: Sun Nov 30 09:20:46 2014 Cross-referenced by PHPXref 0.7.1