niallobrien
5/29/2013 - 12:17 PM

PHP OOP, implementing and interface & dependancy injection.

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();