The 5 Principles of SOLID

The SOLID principles are 5 key principles when it comes to writing (and designing) object orientated programs. The original SOLID theory was introduced in 2000 by Robert C. Martin (although the actual mnemonic acronym 'SOLID' was introduced some years later) and has become a very popular set of principles to adhere to when programming.

The 5 principles of SOLID

Single responsibility principle

The single responsibility principle is a basic but very key concept. I think a lot of programmers somewhat instinctively do this without thinking about it - although once you are aware of this principle and think about it, you will probably end up refactoring some code.

The basic idea is that each class should do one thing, and one thing only.

The class should be provided with all the information or data that it needs, and it should do its one task and that alone.

<?php
class BadlyDesignedBlogClass
{
    public function blog_post($post_id)
    {
        if (!\Auth::check() ) {
            throw new \Exception("You are not logged in! All blog posts are for logged in users "); // not sure why, but for the purposes of this demo...
        }
        $db = $this->connect_to_db();
        $blog_post_sql = "select * from blog_posts where id = ?";
        $post = $this->run_db_query($db,$blog_post_sql, $post_id);
        if (!empty($_POST['title'])) {
            $this->edit_post($post,$_POST['title']);
            echo "<h1><a name="section_saved-edits" id="section_saved-edits"></a>Saved edits!</h1>";
            return true;
        }
        echo "<a name="section_viewing-blog-post-epost-title" id="section_viewing-blog-post-epost-title"></a>Viewing blog post: " . e($post->title) . "";
        echo "Maybe you want to edit it?";
        echo "<form>";
        echo "<input type="text" name="title" value='" . e($post->title) . "'>";
        echo "<input type="submit">";
        echo "</form>";
        return true;
    }

    protected function edit_post(BlogPost $post, $new_title)
    {
        // save it ...
    }

    protected function connect_to_db()
    {
        // do the db connection here...<br>
    }

    protected function run_db_query($db, $sql, $params)
    {
        // do the sql query here...
    }
}

This class would be used like this, in a controller's method:

<?php
class BlogController
{
    public function show($post_id)
    {
        $blog_post = new BadlyDesignedBlogClass();
        $blog_post->view_and_edit_blog_post($post_id);
    }
}

Main problems with BadlyDesignedBlogClass():

  • It does far too much! It does the following things:
    • Checks if the user is logged in.
    • Creates a database connection
    • Queries the database itself
    • Maybe deals with updating the blog post (if $_POST was not empty)
    • Shows the blog post - it echos out HTML

Instead, the class(es) should have one single responsibility

So, time for a rewrite.

I would prefer to use a repository for the database connection and queries. The authentication should be in the controller (really, I'd put it in middleware or in some rules in the routes configuration, but I'm trying to keep this example simple without too many files/classes).

Here is a rewrite.

<?php
class BlogController
{
    protected $blog_repo;
    public function __construct(BlogRepo $blog_repo)
    {
        $this->blog_repo = $blog_repo;
    }
    public function show($post_id)
    {
        if (!\Auth::check()) {
            // actually, I'd prefer to stick this 'behind' the controller, in some middleware for example if using Laravel, or some rules in the routing file. But this example is meant to be quite simple...
            throw new \Exception("You are not logged in - all blog posts are for logged in users ");
        }
        //$blog_post = new BadlyDesignedBlogClass();
        //$blog_post->view_and_edit_blog_post($post_id);
        $blog_post = $this->blog_repo->find($post_id);
        return view("show_blog_post.php", ['blog_post'=>$blog_post]);
    }
    public function update($post_id)
    {
        $blog_post = $this->blog_repo->find($post_id);
        $blog_post->update(['title'=>$_POST['title']);
        // now it is saved, confirm that:
        return view("updated_blog_post.php");
    }
}

class BlogRepo
{
    protected $connection;
    public function __construct($connection)
    {
        $this->connection = $connection;
    }
    public function find($id)
    {
        // query the database for blog_posts with id = $id
    }
}

It is assumed that when BlogController is instantiated, a valid DBConnection gets sent to its constructor. It would be reasonable to just send a BlogRepository (which includes the DBConnection as one of its properties), but for the sake of example I just instantiated it in the controller's method.

The controller now has two methods. These methods get the requested blog post (via the blog repository class), then displays it (show()) or saves submitted changes (update() )

The old class had one method, that sent everything off to BadlyDesignedBlogClass which echoed out content

The new version is much cleaner, easier to test and easier to maintain.

(This example is simplified, I'm not really sure it is a great example to be honest. Maybe I'll rewrite it soon!)

a class should have only a single responsibility (i.e. changes to only one part of the software's specification should be able to affect the specification of the class).

Open/closed principle

The designer of the SOLID principles considered the 'Open/closed principle' the most important one, and it is hard to disagree with him. This principle says that classes (or functions, etc - but we would typically apply it to classes when dealing with PHP) should be open for extension, but closed for modification. This means that your code should be written so that others (or a future you) can modify how it works without having to edit the existing code. When talking about making a class open for extension, the obvious thing to mention is class inheritance and interfaces. The interfaces shouldn't change (closed for modification) - however of course the implementation of these publicly facing methods should be open for extension in subclasses.

Liskov substitution principle

The Liskov substitution principle (known as LSP) is an important concept when it comes to object oriented programming. It basically states that a certain bit of code (to make this example easier to explain, let's just say the 'client class') should be able to use either a base class, or any subclasses of that base class, and the 'client class' would not have to change any of it's own code or logic.

Another way of thinking of it: If you have a (base) class, and then you have five other classes that all extend that base class. Any code that uses the base class should also work if you replace that base class with any of it's subclasses.

See also: design by contract.

Interface segregation principle

The Interface segregation principle (known as ISP) is the principle that states that clients should not be forced to implement interfaces that they don't use. It states that it is better to have many 'thin' interfaces (remember, in PHP you can implement more than one interface in a class) than one huge 'fat' interface.

Dependency inversion principle

This is my favourite of the principles, as it produces much cleaner code which is easier to change at a later date and to test with.

I'll give an example with some PHP - If you have some client class that needs to talk to a database, you could type hint your class called MysqlDBConnection (and use a service container to provide the type hinted object). But then what if you change to SQLite? Do you make a class SQLiteDBConnection extends MysqlDBConnection? It is better if you type hinted DBConnectionInterface, and both of your Mysql/SQLite classes implemented these. Then leave it up to your application (for example, in a service container) to pass the correct object that implements it.

You can then provide different implementations, without having to change your main client code.

Comments The 5 Principles of SOLID