Skip to content

Instantly share code, notes, and snippets.

@diloabininyeri
Created March 22, 2023 11:32
Show Gist options
  • Save diloabininyeri/6fd558d42434969449f988a09afbdbb3 to your computer and use it in GitHub Desktop.
Save diloabininyeri/6fd558d42434969449f988a09afbdbb3 to your computer and use it in GitHub Desktop.
The an example observer design pattern in php
<?php
interface Subscriber
{
public function handle(Blog $blog): void;
}
trait ObserveAble
{
private array $events;
public function share(Subscriber $subscriber): self
{
$this->events[] = $subscriber;
return $this;
}
private function notify(Blog $blog): void
{
foreach ($this->events as $handler) {
$handler->handle($blog);
}
}
}
class Blog
{
public function __construct(private readonly int $id, private readonly string $name)
{
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
}
class Facebook implements Subscriber
{
public function handle(Blog $blog): void
{
echo sprintf(
'id: %d, name: %s will share on facebook',
$blog->getId(),
$blog->getName()
);
}
}
class Linkedin implements Subscriber
{
public function handle(Blog $blog): void
{
echo sprintf(
'id: %d, name: %s will share on linkedin',
$blog->getId(),
$blog->getName()
);
}
}
class Article
{
use ObserveAble;
public function publish(): bool
{
$this->notify(new Blog(12, 'test article'));
return true;
}
}
$article = new Article();
$article
->share(new Facebook())
->share(new Linkedin());
$article->publish();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment