Skip to content

Instantly share code, notes, and snippets.

@iansltx
Created July 18, 2014 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iansltx/2e22a69109f61c2cb839 to your computer and use it in GitHub Desktop.
Save iansltx/2e22a69109f61c2cb839 to your computer and use it in GitHub Desktop.
On-construct ADR content type negotiation
<?php
class MyAction
{
protected $request;
protected $responder;
public function __construct(Aura\Web\Request $request, ResponderInterface $responder) {
// you'd inject other stuff here normally, but let's assume that this is extended elsewhere
$this->request = $request;
$this->responder = $responder;
// throws InvalidArgumentException if not acceptable; handle it in the front controller
// we could also inject a responder chain or the like, to decide which responder to use
$this->responder->setAccept($request->accept);
}
public function __invoke() {
// marshal parameters, call domain logic, etc.
$data = ['id' => 123, 'name' => 'Something Useful'];
// returns a responder, which then gets invoked by the dispatcher to in turn get a response, to render
return $this->responder->setData($data);
}
}
<?php
class MyResponder implements ResponderInterface
{
protected $response;
protected $accept;
protected $data;
protected static $acceptableContentTypes = ['application/json', 'text/csv'];
public function __construct(Aura\Web\Response $res) {
$this->response = $res;
}
public function setAccept(Aura\Web\Request\Accept $accept) {
$this->accept = $accept;
if (!$accept->media->negotiate(static::$acceptableContentTypes)) {
throw new \InvalidArgumentException(implode(',', static::$acceptableContentTypes), 406);
}
return $this;
}
public function setData($data) {
$this->data = $data;
return $this;
}
public function __invoke() {
// build response as needed; CSVs will get built differently than JSON
return $this->response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment