Skip to content

Instantly share code, notes, and snippets.

@mikemix
Last active August 29, 2015 14:02
Show Gist options
  • Save mikemix/cccf1a2be50b8691a080 to your computer and use it in GitHub Desktop.
Save mikemix/cccf1a2be50b8691a080 to your computer and use it in GitHub Desktop.
<?php
class User {
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class ActivityService {
const EVENT_ACTIVITY = 'activity';
protected $evm;
public function __construct(User $user) {
$this->user = $user;
}
public function getEventManager() {
if (! $this->evm) {
$this->evm = new EventManager();
}
return $this->evm;
}
public function trigger($actionObject) {
$this->getEventManager()->trigger(self::EVENT_ACTIVITY, array(
'user' => $this->user,
'object' => $actionObject,
));
}
}
class ActivityMessageStrategy {
public function createMessage(User $user, $object) {
if ($object instanceof StdClass) {
return sprintf('User %s created a standard class, great for him', $user->getName());
}
return sprintf('User %s did an unkown action, shame', $user->getName());
}
}
class ActivityListener {
public function __construct(ActivityMessageStrategy $strategy) {
$this->strategy = $strategy;
}
public function respond(EventInterface $event) {
$user = $event->getParam('user');
$object = $event->getParam('object');
echo $this->strategy->createMessage($user, $object);
}
}
// in onBootstrap()
$service = $sm->getServiceLocator()->get('activityService');
$service->getEventManager()->attach(ActivityService::EVENT_ACTIVITY, array(new ActivityListener(), 'respond'))
$user = new User('Mike');
$service = new ActivityService($user);
// in application
// user creates a class (silly example), eq. do something
$object = new StdClass();
// and notify everyone about that
$service->trigger($object);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment