SOLID Principles

If you’ve been programming in PHP for a while or just programming for that matter then you may have founds ways to improve your code, you know – take it to another level.

All credit goes to Reval Govender for this post, check out the video here – SOLID Principles

Efficiency, Scalability, Maintainability, Extensible and loosely coupled code comes to mind when thinking about advancing your programming skills. Enter SOLID Principles, don’t worry – there will only be 5 of them to keep in mind. You’ll be okay.

The Five SOLID Principles

  1. S – Single Responsibility
  2. O – Open/Close
  3. L – Liskov Subtitution
  4. I – Interface Segration
  5. D – Dependency Inversion

Yeah, I know there are a few phrases in that list that sound really inconsistent with the whole theme. Especially that word – “Liskov”. Look don’t worry, you aren’t alone in your bewilderment. We’ll get through each item on the list and make sure you are up to speed with these SOLID principles.

In this first post of a five part series, I’ll just be giving a general overview of the Single Responsibility Principle – yeah were taking a little baby step forward but at the same time taking a plunge.

The Single Responsibility Principle

A class should have one, and only one, reason to change.

In other words, a class should only have one task, or one responsibility – so if there are any other methods contained within a class that deals with something different, then these methods should be extracted and constructed in another class.

Why the need for a single responsibility

  1. Makes the class easier to maintain
  2. Potentially makes class reusable
  3. Easier to test

Now this post assumes you have general knowledge of OOP PHP – even some basic knowledge. We are about to dive in some code, so here we go.

Let’s start with an example

Suppose we want to resize an image. In this case we would create an ImageHandler class.


<?php

class ImageHandler
{
    protected $image;

    public function __construct($image) 
    {
      $this->image = $image;
    }

    public function validate() 
    {
      // validate image
    }

    public function resize()
    {
      // resize image
    }

    public upload()
    {
      // upload to server
    }
}

At first glance, this class looks A-OK, and it actually it is Okay to roll out with this set up. But we can make it better. First step is to examine the principle of responsibility. If you haven’t already figured it out, that upload() method can be extracted into its own class. Why? Well, uploading an image is an entire responsibility of its own that’s why. More importantly though, this ImageHandler class is responsible for processing the image. The upload() method on the other hand would involve communicating with several servers – both locally and remotely. And this class can get bloated pretty fast. How would this extraction look like?

Stay tuned for the next post