Created
July 18, 2014 23:42
-
-
Save iansltx/2e22a69109f61c2cb839 to your computer and use it in GitHub Desktop.
On-construct ADR content type negotiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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