On Thu, Oct 10, 2013 at 9:53 PM, David Muir <[email protected]> wrote:
> I'm just starting on a new project where I'm wanting to set up my routes to
> work for HTML as well as JSON.
>
> The AbstractRestfulController seemed like a good idea since it automatically
> handles the routing of typical CRUD type actions. What I'm having trouble
> with is how to deal with HTML's anaemic HTTP verb support. If I remember
> correctly, in ZF1, you could send a request and include a METHOD query param
> to route to the non supported verbs, e.g. PUT, DELETE, OPTIONS, HEAD, etc.
> Looking through ZF2's AbstractRestfulController source and documentation, it
> doesn't look like it supports that hack. Are people only using this
> controller for json api's or is there an obvious way to handle it that I'm
> missing?
One thing you can do is alter the Request object's HTTP method based
on the existence of a given query string variable; you could do this
in a listener on the controller's dispatch event at high priority, so
that by the time the default dispatch handler is called, it sees only
the method:
class MyController extends AbstractRestfulController
{
public function setEventManager(EventManagerInterface $events)
{
parent::setEventManager($events);
$events->attach('dispatch', array($this, 'detectHttpMethod'), 100);
return $this;
}
public function detectHttpMethod($e)
{
$request = $e->getRequest();
if (!$request instanceof \Zend\Http\Request) {
return;
}
$method = $request->getQuery('__method', false);
if (!$method) {
return;
}
// likely want to validate the method before injecting
// ...
$request->setMethod($method);
}
}
Essentially, the above looks for a query string parameter named
"__method", and, if detected, sets the request method appropriately.
As noted, you'd want to validate the method before injection.
> Apigility looks really interesting, but I don't think it's the right fit
> setting up the primary interface.
Alternately, I'd actually try something like Apigility, where you
develop the API up front, and then consume it via a JS MVC framework
(we used Angular for Apigility). I was surprised at how much simpler
creating the UI for the Apigility admin was -- and this was in large
part because we focussed on the API first, and what we wanted to
expose. It also meant the logic was a lot simpler on the backend; we
could focus on the business objects only, and not worry about having
multiple representations and worrying about which renderer would win.
You return the same thing all the time, and the client decides what to
do with it.
--
Matthew Weier O'Phinney
Project Lead | [email protected]
Zend Framework | http://framework.zend.com/
PGP key: http://framework.zend.com/zf-matthew-pgp-key.asc
--
List: [email protected]
Info: http://framework.zend.com/archives
Unsubscribe: [email protected]