Zf2 Event, base use

21 Nov 2013 - Tags: zf2, php

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.

<?php
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 [email protected] \n";
}, -10);
$foo->echoHello();

The result

[email protected] eventTest :) $ php try.php
Wow! Hello. This example is very good!

by [email protected]

@see Zend Event Manager Ref