Last active
May 19, 2021 06:05
-
-
Save ksmylmz/17680e4c6295097801ff056d6bb5c49c to your computer and use it in GitHub Desktop.
Observer Design Pattern example
This file contains hidden or 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 | |
class HookService | |
{ | |
public function TrackingHookService() | |
{ | |
$subscriber1 = new Subscriber("http://listener1.com/listenurl",000); | |
$subscriber2 = new Subscriber("http://listener2.com/listenurl",999); | |
$eventPublisher = new EventPublisher(); | |
$eventPublisher->attach($subscriber1); | |
$eventPublisher->attach($subscriber2); | |
$eventPublisher->notify(); | |
} | |
} | |
class Subscriber | |
{ | |
public $listenerPath,$eventCode; | |
public function __construct($listenerPath,$eventCode) | |
{ | |
$this->$listenerPath = $listenerPath; | |
$this->eventCode = $eventCode; | |
} | |
public function update() | |
{ | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $this->listenerPath); | |
curl_setopt($ch, CURLOPT_HEADER, TRUE); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); | |
curl_setopt($s,CURLOPT_POST,true); | |
curl_setopt($s,CURLOPT_POSTFIELDS,["eventCode"=>$this->eventCode]); | |
curl_exec($ch); | |
curl_close($ch); | |
} | |
} | |
class EventPublisher | |
{ | |
private $subScribers=[]; | |
public function attach(Subscriber $subscriber) | |
{ | |
$subscriber[] =$subscriber; | |
} | |
public function detach($index) | |
{ | |
$subscriber[] =$subscriber; | |
} | |
public function notify() | |
{ | |
foreach ($this->subScribers as $subscriber) | |
{ | |
$subscriber->update(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment