Skip to content

Instantly share code, notes, and snippets.

@alanpich
Created June 4, 2014 16:19
Show Gist options
  • Save alanpich/14ef809c1d3bd42ee931 to your computer and use it in GitHub Desktop.
Save alanpich/14ef809c1d3bd42ee931 to your computer and use it in GitHub Desktop.
Example of using PHP Interfaces
<?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();
}
<?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;
}
}
<?php
interface MessageInterface
{
public function setRecipient($recipient);
public function setContent($content);
public function send();
}
<?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