in php oop refactor object oriented programming solid ~ read.

Loose Coupling in PHP

In this post, we are going to talk about what is Loose Coupling in PHP.

What is Loose Coupling?

Here is a rather great article if you want to understand more about what is Loose Coupling. Have you ever experienced the situation that a change of a class influence the other classes? And Loose Couple means that we as developer should try to reduce the impact of a change from one class to other classes.

What is Loose Coupling important?

One of the reason like I mentioned before that if a change in one class always cause a lot of impact in other classes, you will be more afraid of modifying your code base, and as time goes on, your code will rot, which will lead to the failure of your project. So in a simple term, it is extremely important.

How to achieve Loose Coupling code?

Let's have a look at the following code.

<?php  
class CustomerRepository  
{
    private Database $database;

    public function CustomerRepository(Database $database)
    {
        $this->database = $database;
    }

    public function Add($customerName)
    {
        $this->database->addRow("Customer", $customerName);
    }
}

class Database  
{
    public function addRow($table, $value)
    {
    }
}

(Tight Coupling Code)

As you can see here that CustomerRepository class totally depends on the Database class which means that CustomerRepository won't work without Database class and any change to either one of the class might have impact to the other one.

How can we make it a little bit dependent with each other but yet still achieve the same functionality as we needed.

<?php  
interface IDatabase  
{
    public function addRow($table, $value);
}

class CustomerRepository  
{
    private IDatabase $database;

    public function CustomerRepository(IDatabase $database)
    {
        $this->database = $database;
    }

    public function Add($customerName)
    {
        $this->database->addRow("Customer", $customerName);
    }
}

class Database implements IDatabase  
{
    public function addRow($table, $value)
    {
    }
}

(Loose Coupling Code)

As you can see at the above that we introduce an interface called IDatabase which break the coupling between Database class and CustomerRepository class. So from now on any changes to CustomerRepository doesn't care about Database class as long as it implements the same interface.

End

Thanks for reading this post and I hope you can start using this technique into your coding. If you have any opinions or ideas please leave it below. Thanks!

comments powered by Disqus