Created
May 29, 2013 12:17
-
-
Save niallobrien/5669865 to your computer and use it in GitHub Desktop.
PHP OOP, implementing and interface & dependancy injection.
This file contains 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 | |
// Define the methods that must be implemented | |
interface MailerInterface | |
{ | |
public function addEmail($email); | |
public function send(); | |
} | |
// Implement the Interface methods in this class | |
class SwiftmailMailer implements MailerInterface | |
{ | |
protected $emails; | |
public function addEmail($email) | |
{ | |
// Push each new email on to an array | |
$this->emails[] = $email; | |
} | |
public function send() | |
{ | |
// Resolve the Swiftmailer object from the IoC, add the $emails to it & send | |
$this->app->make('swiftmailer')->addTo($this->emails)->send(); | |
} | |
} | |
// Implement the Interface methods in this class | |
class FakeMailer implements MailerInterface | |
{ | |
public function addEmail($email) | |
{} | |
public function send() | |
{} | |
} | |
<?php | |
class Sender | |
{ | |
// Typehint MailerInterface and use direct injection to inject the $mailer object | |
public function __construct(MailerInterface $mailer) | |
{ | |
$this->mailer = $mailer; | |
} | |
public function send() | |
{ | |
$this->mailer->addEmail('[email protected]'); | |
$this->mailer->send(); | |
} | |
} | |
// Example usage | |
<?php | |
// this will send real emails | |
$realSender = new Sender(new SwiftmailMailer); | |
$realSender->send(); | |
// this will not | |
$fakeSender = new Sender(new FakeMailer); | |
$fakeSender->send(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment