如何(或在哪里)使用Zend Framework 2的EventManager?

I am trying to use the new Eventmanager of the Zend Framework 2. I do understand the basic usage. But i´m not sure how to use this in a real project or rather where to go with the code.

For example: In the introduction from Rob Allen (link above) he triggers two events in the "findById" Method. Where should the code for the listeners go to? In my opinion it doesn´t make sense to put this code also in the PhotoMapper class or am i wrong?

I confess that I have not played with it strongly yet, but I think you are right that the listener code should probably not be in the mapper. Rather, it can stand alone in an external class so it can really be a single-responsibility object - handling the events to which he subscribes - and the code can stay as DRY as possible.

As a first step, we can define what the listener needs to to do his job. Some things he knows on instantiation, others need to passed when the event is triggered.

For example, for a cache listener, I might instantiate him at Bootstrap with info about where to cache, lifetime, etc. Perhaps even grab a cache instance fully configured and ready to go from the cachemanager resource. These could be constructor params for the listener object.

Then, still probably at Bootstrap, I would register this listener with the event manager, subscribing to your event and attaching the method you wish to run when the event is triggered. Of course, that method signature needs to be compatible with the information that the event manager will give you.

I guess the idea is that this listener object has the potential benefits of:

  1. being single-responsibilty, so lower complexity and easier to test

  2. hopefully being sufficiently general so that this single listener can handle multiple events.

There is a little wrinkle here. It might seem like unreasonable performance hit to instantiate and register a listener just on the chance that some downstream process might trigger the event to which he is subscribed. That's where static listeners come in. Again, the registration is done early (like Bootstrap), but the listener is not instantiated until he is really needed.

Disclosure: I might have this completely wrong. So if someone wants to straighten me out, that would be great. ;-)