phly / PhlyRestfully

ZF2 module for creating RESTful JSON APIs using HAL and API-Problem
108 stars 45 forks source link

Question Regarding Listeners #63

Closed pulpfree closed 11 years ago

pulpfree commented 11 years ago

I really enjoyed your articles on working restfully with ZF2 and have an application requiring an API so decided to implement this PhlyRestfully module. Admittedly my experience with the ZF2 EventManager is a little limited and I've been trying to understand how the Resource Listener actually works. In your documentation I understand that it's the listeners job to persist data. For example I'm assuming when the Resource::fetch($id) is called it is the listener's job to do the actual fetching via a db extraction class or similar. If these assumptions are correct, then how would I actually do that in the listener?

I believe I found the answer with: Phpbnl13StatusApi / StatusDbPersistence.php

weierophinney commented 11 years ago

The listener will actually typically delegate persistence to another object; its job is to marshal the arguments provided (identifier, if present; data, if present; potentially route and/or query parameters; etc.), and pass it on to something capable of persisting the data. Often, I might have validation in this listener as well, so I can skip the persistence entirely if unable to validate.

As for a concrete example -- yes, the StatusDbPersistence class from the Phpbnl13StatusApi repo is a good example. Note that I compose the persistence layer -- the table object -- within that listener, and then operate on it. (The Module class from that repo also demonstrates a number of other listeners on events that PhlyRestfully triggers.)