Skip to content

Instantly share code, notes, and snippets.

@netojoaobatista
Created February 13, 2013 14:51
Show Gist options
  • Save netojoaobatista/4945088 to your computer and use it in GitHub Desktop.
Save netojoaobatista/4945088 to your computer and use it in GitHub Desktop.
Simulação dos grupos do Facebook utilizando Mediator
<?php
class Colleague extends Hashed
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function join(Group $group)
{
$group->add($this);
}
public function send(Message $message, Group $group)
{
$group->send($message, $this);
}
public function receive(Message $message, Colleague $from,
Group $group)
{
printf("Notificação para %s\n", $this->name);
printf("\t %s publicou no grupo %s:\n", $from->name, $group->getName());
printf("\t%s\n\n", $message->getContent());
}
}
<?php
class Group extends Hashed
{
private $mediator;
private $name;
public function __construct(GroupMediator $mediator, $name)
{
$this->mediator = $mediator;
$this->name = $name;
}
public function add(Colleague $colleague)
{
$this->mediator->add($colleague, $this);
}
public function getName()
{
return $this->name;
}
public function send(Message $message, Colleague $from)
{
$this->mediator->send($message, $from, $this);
}
}
<?php
class GroupMediator
{
private $colleagues = array();
public function add(Colleague $colleague, Group $group)
{
$groupHash = $group->getHash();
if (!isset($this->colleagues[$groupHash])) {
$this->colleagues[$groupHash] = array();
}
$this->colleagues[$groupHash][$colleague->getHash()] = $colleague;
}
public function send(Message $message, Colleague $from, Group $group)
{
$fromHash = $from->getHash();
$groupHash = $group->getHash();
if (!isset($this->colleagues[$groupHash][$fromHash])) {
throw new RuntimeException(
'Você precisa entrar no grupo para poder enviar mensagens');
}
foreach ($this->colleagues[$groupHash] as $hash => $colleague) {
if ($hash !== $fromHash) {
$colleague->receive($message, $from, $group);
}
}
}
}
<?php
class Hashed
{
private $hash;
public function getHash()
{
if ($this->hash === null) {
$this->hash = spl_object_hash($this);
}
return $this->hash;
}
}
<?php
class Message
{
private $content;
public function __construct($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment