Zf2 Event, base use

21 Nov 2013 · Less than one minute read · on Gianluca's blog

Hi! Some mouths ago I have writted a gist for help me to remember a base use of Events and Event Manager into Zend Fremework, in this article I report this small tutorial.

require_once __DIR__."/vendor/autoload.php";

class Foo
    /* @var \Zend\EventManager\EventManagerInterface */
    protected $eventManager;

    public function getEventManager()
        if(!$this->eventManager instanceof \Zend\EventManager\EventManagerInterface){
            $this->eventManager = new \Zend\EventManager\EventManager();
        return $this->eventManager;

    public function echoHello()
        $this->getEventManager()->trigger(__FUNCTION__."_pre", $this);
        echo "Hello";
        $this->getEventManager()->trigger(__FUNCTION__."_post", $this);

$foo = new Foo();
$foo->getEventManager()->attach('echoHello_pre', function($e){
    echo "Wow! ";
$foo->getEventManager()->attach('echoHello_post', function($e){
    echo ". This example is very good! \n";
$foo->getEventManager()->attach('echoHello_post', function($e){
    echo "\nby gianarb92@gmail.com \n";
}, -10);

The result:

gianarb@GianArb-2 eventTest :) $ php try.php
Wow! Hello. This example is very good!

by gianarb92@gmail.com

@see Zend Event Manager Ref

Something weird with this website? Let me know.