Abstract classes, abstract methods, interfaces, what? post

If you've been developing with PHP for any length of time you've probably heard of concrete classes, abstract classes, abstract methods, and interfaces. Many of the popular frameworkd encourage you to "program to an interface", but what does that mean? And when should you program to an abstract class, or define an abstract method? Let's figure this out.

What's what?

I could give you definitions, but most people have a hard time wrapping their heads around these ideas without examples. I'd like for us to incrementally learn with a "real" life example. You won't find any car, animal, or whatever weird metaphors you have to figure out how to translate to real use cases here.

Starting small

First things first, let's define a small, achievable goal. Our application needs to be able to email its users. Let's accomadate that. We would probably write a class like this.

class BasicEmail 
{
    private $email;

    private $body;

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function setBody($body)
    {
        $this->body = $body;
    }

    protected function isValid()
    {
        return is_email($this->email) && strlen($this->body) > 0;
    }

    public function attempt()
    {
        if($this->isValid())
        {
            $this->send();
        }
    }

    public function send()
    {
        //use $email and $body to send email
    }
}

//elsewhere in your application

$email = new BasicEmail;
$email->setEmail('johnDoe@gmail.com');
$email->setBody('Thanks for joining CatLoverApp, the social media platform to show off your cat!');
$email->attempt();


Sweet. That looks good. We're using object oriented programming! Let's continue on.

Your users are really enjoying getting emails when their friends post pictures of their cats. Things are good, except many users are requesting SMS messages to be sent in addition to emails. A service like Twilio is perfect for this. Let's use it.

class SMS 
{
    private $phone;

    private $text;

    public function setPhone($phone)
    {
        $this->phone = $phone;
    }

    public function setText($text)
    {
        $this->text = $text;
    }

    protected function isValid()
    {
        return is_phone($this->phone) && strlen($this->text) > 0;
    }

    public function attempt()
    {
        if($this->isValid())
        {
            $this->send();
        }
    }

    public function send()
    {
        //use Twilio to send SMS
    }
}

//elsewhere in your application

$sms = new SMS;
$sms->setPhone('123-456-7890');
$sms->setText('Bob, just posted a pic of his cat!');
$sms->attempt();


Abstract classes and methods

Cool, now we can send emails and SMS messages to our users...but our classes look very similar. That doesn't feel quite right. They both have a destination, text body, isValid(), attempt(), and send() methods. This is the perfect scenario for an abstract class. That could look like this.

abstract class Message 
{
    private $destination;

    private $content;

    public function setDestination($destination)
    {
        $this->destination = $destination;
    }

    public function setContent($content)
    {
        $this->content = $content;
    }

    public function attempt()
    {
        if($this->isValid()) {
            $this->send();
        }
    }

    abstract protected function isValid();

    abstract public function send();
}

class BasicEmail extends Message 
{
    protected function isValid()
    {
        return is_email($this->destination) && strlen($this->content) > 0;
    }

    public function send()
    {
        //use $this->destination and $this->content to send email
    }
}

class SMS extends Message 
{   
    protected function isValid()
    {
        return is_phone($this->destination) && strlen($this->content) > 0;
    }

    public function send()
    {
        //use $this->destination and $this->content to send SMS
    }
}

//

$message = new Message; //Invalid, won't work because it's abstract!

$message1 = new BasicEmail;
$message1->setDestination('johnDoe@gmail.com');
$message1->setContent('Sorry, Susan just de-friended you!');
$message1->attempt();

$message2 = new SMS;
$message2->setDestination('123-456-7890');
$message2->setContent('Sorry, Susan just de-friended you!');
$message2->attempt();


We can use abstract classes when we have similar objects that share some functionality but do things a bit differently. In our Message class we've defined a couple abstract methods. We are forcing a requirement on all classes that extend Message. We require them to implement send() and isValid() methods. The Message class doesn't care how exactly it sends the message or how it gets validated, just that it has the ability to do so.

It's also important to note that abstract classes and interfaces(which we'll get to later) can define methods with any type of visibility, public, protected, or private. In these classes, the isValid() should probably be public. I'm merely illustrating a point.

Warning! You can not instantiate an abstract class. They're too vague. They're meant to be extended.
Note! If a class has an abstract method defined, it must be an abstract class. However, it is still valid to define an abstract class that has zero abstract methods. It's uncommon, but valid.

Message queue

We can't predict the future and can't know what our users will want next. Maybe an actual phone call, who knows? We do know that they like notification options and want lots of them. Let's put together some kind of message queue. Our first pass might look like this.

$messages = array();

$messages[] = $message1;
$messages[] = $message2;

/** other application code **/

foreach ($messages as $message) {
    $message->attempt();    
}


Hmm...this works, but it could be a lot better. What happens if our coworker, Norm, sees $messages and adds $messages[] = "You've been awarded a badge!"? Things break. He might not have seen the portion of code that sends all of the messages and expects them to have an attempt() method. For our and our coworkers sake, let's refactor. Let's create an actual MessageQueue.

class MessageQueue 
{
    private $messages = array();

    public function add(Message $message)
    {
        $this->messages[] = $message;
    }

    public function sendAll()
    {
        foreach ($this->messages as $message) {
            $message->attempt();
        }
    }
}


This looks a lot better. We're even type-hinting the add() method! Our coworkers will know that the add() method requires only Message objects(which BasicEmail and SMS are).

Extending functionality

I'm liking this MessageQueue idea. It doesn't care what kind of Message it's sending, just that it needs to send them. This is great.

Now, let's say we want to really encourage our users to use our service. Let's reward them 5¢ for every cat photo they post.

class PhotoReward 
{
    private $amount;

    private $recipient;

    public function setAmount($amount)
    {
        $this->amount = $amount;
    }

    public function setRecipient($recipient)
    {
        $this->recipient = $recipient;
    }

    public function reward()
    {
        //use paypal to send reward to recipient
    }
}


This doesn't qualify as a Message but it would be great if we could use it in a queue. Time for an interface! An interface imposes requirements on our classes in the form of methods, just like abstract methods, only there's zero implementation code.

One advantage to using interfaces is that you can bolt them on to your existing classes. A class can only extend a single other class. It can only have one parent. When it comes to interfaces, however, classes can implement an unlimited number of interfaces.

Fun Fact! Interfaces can be extended by other interfaces. I don't think I've seen it done out in the wild, but it can be. Usually it's clearer to just have your classes implement multiple interfaces.

Let's define an Event interface.

interface Event 
{
    public function fire();
}


As you can see, the interface does nothing but define a fire() method. Any class that uses/implements this interface will be required to define a fire() method.

Time to refactor our queue class. Let's genericize it a bit by using the Event interface.

class EventQueue 
{
    private $events = array();

    public function add(Event $event)
    {
        $this->events[] = $event;
    }

    public function fireAll()
    {
        foreach ($this->events as $event) {
            $event->fire();
        }
    }
}


Now, let's refactor our other Message and PhotoReward classes to use the interface.

abstract class Message implements Event 
{
    private $destination;

    private $content;

    public function setDestination($destination)
    {
        $this->destination = $destination;
    }

    public function setContent($content)
    {
        $this->content = $content;
    }

    public function attempt()
    {
        if($this->isValid()) {
            $this->send();
        }
    }

    public function fire()
    {
        $this->attempt();
    }

    abstract protected function isValid();

    abstract public function send();
}

class PhotoReward implements Event 
{
    private $amount;

    private $recipient;

    public function setAmount($amount)
    {
        $this->amount = $amount;
    }

    public function setRecipient($recipient)
    {
        $this->recipient = $recipient;
    }

    public function fire()
    {
        $this->reward();
    }

    public function reward()
    {
        //use paypal to send reward to user
    }
}


Lookin good. There are few things to note.

You'll notice that we didn't need to touch the BasicEmail and SMS classes. We set the interface on their parent abstract Message class. The new fire() method just wraps our attempt() method. This may seem redundant, but we are now able to call these classes Events.

We could have kept the interface on Message and left off the fire() method because Message is abstract. As long as the implementations, BasicEmail and SMS, implemented their own fire() methods, they would adhere to the interface. All abstract requirements are eventually funnelled down to their concrete implementations.

We've implemented an interface on an abstract and a concrete class. Both are valid.

Let's see what we can do now.

$queue = new EventQueue;

$event1 = new BasicEmail;
$event1->setDestination('johnDoe@gmail.com');
$event1->setContent('Sorry, Susan just de-friended you!');

$queue->add($event1);

$event2 = new SMS;
$event2->setDestination('123-456-7890');
$event2->setContent('Sorry, Susan just de-friended you!');

$queue->add($event2);

$event3 = new PhotoReward;
$event3->setRecipient($bob);
$event3->setAmount(5);

$queue->add($event3);

$queue->fireAll();


Because each object adheres to the Event interface, we can add them to the queue and the queue can count on all of its objects to have a fire() method. Sweet.

Inception

Prepare yourselves. We're about to get crazy.

Let's add some dimension to our EventQueue. You'll notice we have a fireAll() method. This class would also make sense to be an Event. It's time to really take advantage of some object oriented programming.

Our new and improved EventQueue could look like this.

class EventQueue implements Event 
{
    private $events = array();

    public function add(Event $event)
    {
        $this->events[] = $event;
    }

    public function fire()
    {
        foreach ($this->events as $event) {
            $event->fire();
        }
    }
}


What does this buy us? Organization and options.

$messageQueue = new EventQueue;
$rewardQueue  = new EventQueue;

$email = new BasicEmail;
$email->setDestination('johnDoe@gmail.com');
$email->setContent('Congrats, you\'re the cat lover of the month!');

$messageQueue->add($email);

$sms = new SMS;
$sms->setDestination('123-456-7890');
$sms->setContent('Congrats, you\'re the cat lover of the month!');

$messageQueue->add($sms);

$photoReward = new PhotoReward;
$photoReward->setRecipient($bob);
$photoReward->setAmount(5);

$rewardQueue->add($photoReward);

$badgeReward = new BadgeReward;
$badgeReward->setRecipient($spencer);

$rewardQueue->add($badgeReward);

$masterQueue = new EventQueue;
$masterQueue->add($messageQueue);
$masterQueue->add($rewardQueue);

//fire events in both queues
$masterQueue->fire();

//or only fire events in $messageQueue
$messageQueue->fire();

//or only fire events in $rewardQueue
$rewardQueue->fire();


We can now treat and handle each queue separately or all at once. It's now possible to put queues inside of queues inside of queues. Dominic Cobb would be proud.

A side effect of using abstract classes and interfaces is having very modulized and extendable code. To create a new Message we just need to extend the Message class and implement send() and isValid() methods.

Need another example?

Let's pretend we have some documents we need to save to a database. We could have the following abstract class.

abstract class Document 
{
    protected $datasource;

    public function __construct(DataSource $datasource)
    {
        $this->datasource = $datasource
    }

    public function save()
    {
        if($this->isNew())
        {
            return $this->datasource->insert($this);
        }

        return $this->datasource->update($this);        
    }

    public function delete()
    {
        return $this->datasource->delete($this);
    }

    public function set(array $attr)
    {
        //set attributes on the document
    }

    public function isNew()
    {
        //return true or false
    }

    public function getTable()
    {
        return static::TABLE;
    }
}

class Person extends Document 
{    
    const TABLE = "people";
}

class Company extends Document 
{    
    const TABLE = "companies";
}
Gripe! One feature I find lacking from php is the concept of final variables. Let me pick on Laravel a bit to illustrate this point.

In the previous code snippet, we refer to a DataSource. We should definitely define a DataSource interface and code implementations to that.

interface DataSource 
{
    public function insert(Document $document);

    public function update(Document $document);

    public function delete(Document $document);

    public function read($id, Document $document);
}

class MySQLDataSource implements DataSource 
{    
    public function insert(Document $document)
    {
        //use mysql specific code to insert a document
    }

    public function update(Document $document)
    {
        //use mysql specific code to update a document
    }

    public function delete(Document $document)
    {
        //use mysql specific code to delete a document
    }

    public function read($id, Document $document)
    {
        //use mysql specific code to read a document
    }
}

class FileSystemDataSource implements DataSource 
{
    //implement DataSource for file system
}

class RedisDataSource implements DataSource 
{
    //implement DataSource for Redis
}

class MongoDBDataSource implements DataSource 
{
    //implement DataSource for MongoDB
}

By programming to an interface, we can extremely easily swap out components. Consider the following example.

$john = new Person(new MySQLDataSource);
$john->set(["name" => "John Doe"]);
$john->save();

$bob = new Person(new RedisDataSource);
$bob->set(["name" => "Bob Smith"]);
$bob->save();

Because we've defined an interface and created different implementations, we've decoupled our Documents. Swapping things out is a breeze and we've future proofed our application a bit. If a new data source becomes available, we can implement a DataSource for the new data source and swap that in without touching our Document class. Our MySQLDataSource could use the getTable() method to determine where to save/delete the document while our RedisDataSource could use the document's class name. The document isn't concerned with how the DataSource operates, just that it does.

Make sense?

These are difficult concepts to grasp. I hope I've illustrated their usefullness clearly and in a way you can apply to your own codebase. Abstraction is a powerful thing. Learn how to harness its flexibility.

Good luck!

Categories: PHP

Tags: PHP, Intermediate