I'm trying to get a deeper understanding of events in ZF2. After a lot of
reading and experimentation I think I have come up with an optimal solution
that will satisfy my requirements:
1) Allow listeners to modify the calling params
2) Allow called method to be short circuited by a listener
3) Allow listeners to get calculated result
4) Be as compact as possible

(Here's a gist in case the code formatting looks bad:
https://gist.github.com/poisa/6724548)

public function findMemberById($id)
{
    $params =
$this->getEventManager()->prepareArgs(compact(func_get_args()));
    $result = $this->getEventManager()->trigger(__FUNCTION__ . '.pre',
$this, $params, function ($listenerOutput) {
    return ($listenerOutput != null);
    });
    extract((array)$params);
    if ($result->stopped()) {
        return $result->last();
    }

    // Expensive calls here

    $params['__RESULT__'] = $calculatedResult;
    $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this,
$params);

    return $calculatedResult;
}

My only problem with this is that I have something of a code smell here:
"extract((array)$params);" which I don't know how to solve. The reason
behind that line is satisfying requirement #1. Otherwise, in order to
access the modified params, the rest of the method would need to get them
from $params and I think it makes the method less readable.

Can anyone please advise on a better solution?

Thanks,
Julian.

Reply via email to