Skip to content

Instantly share code, notes, and snippets.

@niallobrien
Created May 29, 2013 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niallobrien/5669865 to your computer and use it in GitHub Desktop.
Save niallobrien/5669865 to your computer and use it in GitHub Desktop.
PHP OOP, implementing and interface & dependancy injection.
<?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('bob@bob.com');
$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