-
-
Save poisa/6766923 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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