Created
June 4, 2014 16:19
-
-
Save alanpich/14ef809c1d3bd42ee931 to your computer and use it in GitHub Desktop.
Example of using PHP Interfaces
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 | |
// Example usage | |
if($myMessage instanceof MessageInterface){ | |
// Because $message implements MessageInterface, we | |
// can be absolutely sure that it has a send() method | |
// so don't have to care what it does when sending, | |
// just that it has the capability to send | |
$message->send(); | |
} |
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 | |
lass EmailMessage implements MessageInterface | |
{ | |
protected $content; | |
protected $recipient; | |
protected $subject = 'Hello World'; | |
public function send(){ | |
mail($this->recipient,$this->subject,$this->content); | |
} | |
public function setRecipient($recipient){ | |
if(! isEmailAddress($recipient)){ | |
throw new Exception("{$recipient} is not a valid email address"); | |
} | |
$this->recipient = $recipient; | |
} | |
public function setContent($content){ | |
$this->content = $content; | |
} | |
} |
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 | |
interface MessageInterface | |
{ | |
public function setRecipient($recipient); | |
public function setContent($content); | |
public function send(); | |
} |
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 TextMessage implements MessageInterface | |
{ | |
protected $recipient; | |
protected $content; | |
protected $smsApi; | |
public function send(){ | |
$smsApi->sendText($this->recipient,$this->content); | |
} | |
public function setRecipient($recipient){ | |
if(! isPhoneNumber($recipient)){ | |
throw new Exception("{$recipient} is not a valid UK phone number!") | |
} | |
$this->recipient = $recipient; | |
} | |
public function setContent($content){ | |
if(strlen($content) > 140 ){ | |
throw new Exception("Content is too long to send as a txt message!"); | |
} | |
$this->content = content; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment