Skip to content

Instantly share code, notes, and snippets.

@diloabininyeri
Created October 17, 2022 21:56
Show Gist options
  • Select an option

  • Save diloabininyeri/08426f4263af324f98955d49a916f1ae to your computer and use it in GitHub Desktop.

Select an option

Save diloabininyeri/08426f4263af324f98955d49a916f1ae to your computer and use it in GitHub Desktop.
PHP observer design pattern example
<?php
/**
*
*/
interface HandleInterface
{
/**
* @param Content $content
* @return mixed
*/
public function handle(Content $content);
}
/**
*
*/
interface Content
{
/**
* @return string
*/
public function getContent(): string;
/**
* @return string
*/
public function getUser(): string;
}
/**
*
*/
interface Notification
{
/**
* @param HandleInterface $handle
* @return $this
*/
public function attach(HandleInterface $handle): self;
/**
* @param HandleInterface $handle
* @return $this
*/
public function detach(HandleInterface $handle): self;
/**
* @return void
*/
public function notify(): void;
}
/**
*
*/
class Post implements HandleInterface
{
/**
* @param Content $content
* @return void
*/
public function handle(Content $content): void
{
echo sprintf('post =>user: %s,content: %s',
$content->getUser(),
$content->getContent()
);
}
}
/**
*
*/
class Comment implements HandleInterface
{
/**
* @param Content $content
* @return mixed
*/
public function handle(Content $content)
{
echo sprintf('comment =>user: %s,content: %s',
$content->getUser(),
$content->getContent()
);
}
}
/**
*
*/
class Notify implements Notification, Content
{
/**
* @var SplObjectStorage|HandleInterface[] $notifications
*/
private SplObjectStorage $notifications;
/**
*
*/
public function __construct()
{
$this->notifications = new SplObjectStorage();
}
/**
* @return string
*/
public function getContent(): string
{
return 'user has notification';
}
/**
* @return string
*/
public function getUser(): string
{
return 'admin';
}
/**
* @return $this
*/
public function attach(HandleInterface $handle): Notification
{
$this->notifications->attach($handle);
return $this;
}
/**
* @return $this
*/
public function detach(HandleInterface $handle): Notification
{
$this->notifications->detach($handle);
return $this;
}
/**
* @return void
*/
public function notify(): void
{
foreach ($this->notifications as $notification) {
$notification->handle($this);
}
}
}
$notify = new Notify();
$notify
->attach(new Post())
->attach(new Comment());
$notify->notify();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment