Skip to content

Instantly share code, notes, and snippets.

@poisa
Forked from Thinkscape/AbstractCello.php
Created September 30, 2013 17:08
Show Gist options
  • Save poisa/6766923 to your computer and use it in GitHub Desktop.
Save poisa/6766923 to your computer and use it in GitHub Desktop.
<?php
abstract class AbstractCello
{
/**
* @var EventManager
*/
protected $em;
protected function triggerPre($methodName, $params)
{
$e = new Event($methodName.'.pre', $this, $params);
$result = $this->em->trigger($e, function($o){ return $o !== null; });
if(($lastResult = $result->last()) !== null){
return $lastResult;
}
}
// ... em getters and setters
}
<?php
use Zend\EventManager\Event
class Cello extends AbstractCello
{
public function foo($a, $b = 15, $c = 'bar')
{
if($result = $this->triggerPre(__FUNCTION__,[
'a' => &$a, // we're using references to be able
'b' => &$b, // to modify call params
'c' => &$c // on the spot...
])){
return $result;
}
// expensive calls
return $something;
}
}
<?php
use Zend\EventManager\Event;
$cello = new Cello();
$cello->getEvents()->attach('foo.pre',function(Event $e){
if($event->getParam('a') == 'foo'){
// override the value of param b
$event->getParam('b') == 1024;
}elseif($event->getParam('a') == 'bar'){
// short-circuit execution of foo() method
return 'some result';
}
});
var_dump($cello->foo('foo', 20)); // this will always have the second param === 1024
var_dump($cello->foo('bar')); // this should always return "some result"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment