Skip to content

Instantly share code, notes, and snippets.

@thiagophx
Created February 11, 2012 00:09
Show Gist options
  • Save thiagophx/1794277 to your computer and use it in GitHub Desktop.
Save thiagophx/1794277 to your computer and use it in GitHub Desktop.
ViewHandler
<?php
namespace MyApp;
class HtmlHandler implements ViewHandler
{
public function __invoke(Response $response)
{
foreach ($response->getHeaders() as $header)
header($header);
$response = $response->getData();
return $response;
}
}
<?php
namespace MyApp;
class JsonHandler implements ViewHandler
{
public function __invoke(Response $response)
{
header('Content-Type: application/json');
foreach ($response->getHeaders() as $header)
header($header);
return json_encode($response->getData());
}
}
<?php
namespace MyApp;
class Response
{
protected $data;
protected $template;
protected $headers;
public function __construct(array $data, $template = null)
{
$this->data = $data;
$this->template = $template;
$this->headers = array();
}
public function addHeader($header)
{
$this->headers[] = $header;
}
public function getHeaders()
{
return $this->headers;
}
public function getData()
{
return $this->data;
}
}
$c = new Respect\Config\Container('application.ini');
$c-router->get('/users', 'MyApp\Controller\Users')
->accept(array('.json' => $c->jsonHandler, 'text/html' => $c->htmlHandler));
<?php
namespace MyApp\Controller;
use MyApp\Response;
use Respect\Rest\Routable;
class Users implements Routable
{
public function get()
{
$response = new Response(array(
'users' => array()
));
return $response;
}
}
<?php
namespace MyApp;
interface ViewHandler
{
public function __invoke(Response $response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment