I am learning decorator design pattern in PHP. Please see what i am doing is correct or wrong, would appreciate your review, feedback, comments, suggestions.
<?php
/**
* NotifierService interface is used as abstraction for Notification Mechanism
*
* It can be later implemented as EmailNotifierService, PushNotifierService, or
* any other Notification SErvice
*/
interface NotifierService {
public function Notify();
}
/**
* EmailNotifierService - is Email Decorator
* here the EmailSending is Implemented, and it can be used wherever it is
* required, Different Unique services that doesn not have common behaviours
* are utilised using decorator patterns
*/
class EmailNotifierService implements NotifierService {
public function __construct(){
$this->to = '[email protected]' ;//$toarr;
$this->from = '[email protected]' ;//$from;
$this->msg = 'This is a test message';//$msg
}
/**
* [sendMail Actual Implementation of Sending Email is put here]
* Kept simple for demo purposes
*/
private function sendMail(){
echo "Sending Email To" .PHP_EOL;
print_r($this->to);
echo "From: " .PHP_EOL;
print_r($this->from);
echo "Msg: " .PHP_EOL;
print_r($this->msg);
}
/**
* [Notify - Implementation of the interface method - Notify]
*/
public function Notify(){
echo "Notify function called" .PHP_EOL;
$this->SendMail();
}
}
class User implements NotifierService{
var $users = [];
var $notifierservice;
//Passing NotifierService Object, So that we can utilise its service
public function __construct(NotifierService $notifierservice){
echo "New User constructed";
$this->notifierservice = $notifierservice;
}
/**
* [adduser This function creates a new user, like new user signup,
* Whenever a new user signup, a Email is sent to the Website Admin]
* @param [Username] $u Username
*/
public function adduser($u){
$this->users[]=$u;
$this->Notify();// Calls the Notification
}
public function Notify(){
$this->notifierservice->Notify();
}
}
// New User is created, EmailNotificationService is wrapped in it
// So that whenever a new user is created, Admin gets an Email
$u1 = new User(new EmailNotifierService());
$u1->adduser('Ramkumar');