Skip to content

Instantly share code, notes, and snippets.

@Thinkscape
Last active December 24, 2015 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Thinkscape/6751016 to your computer and use it in GitHub Desktop.
Save Thinkscape/6751016 to your computer and use it in GitHub Desktop.
For Julian
<?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