Web Development
04-02-2024

Dependency Inversion

Dmytro Tus
Full Stack Web developer

Dependency inversion stands for high level modules should not depend on low level modules.

Modules should depend on abstractons, not on implementations.

 

Bad approach:

<?php

class MysqlConnection {
    public function connect() {
        echo'mysql is connected';
        return;
    }
}

class PasswordReminder{
    public function __construct(
        public MysqlConnection $dbConnection
    ) {
    }

    public function remind() {
        $this->dbConnection->connect();
        // get the data from db;
        // send the password
    }
}

$dbConnection = new MysqlConnection();
$pass = new PasswordReminder($dbConnection);
$pass->remind();

 

Good approach

<?php

interface DbConnectionInterdface{
    public function connect();
}

class MysqlConnection implements DbConnectionInterdface {
    public function connect() {
        echo 'mysql is connected';
        return;
    }
}

class PgsqlConnection implements DbConnectionInterdface {
    public function connect() {
        echo 'postrgreSQL is connected';
        return;
    }
}

class PasswordReminder{
    public function __construct(
        public DbConnectionInterdface $dbConnection
    ) {
    }

    public function remind() {
        $this->dbConnection->connect();
        // get the data from db;
        // send the password
    }
}

$dbConnection = new MysqlConnection();
$pass = new PasswordReminder($dbConnection);
$pass->remind();

$dbConnection = new PgsqlConnection();
$pass = new PasswordReminder($dbConnection);
$pass->remind();

Tags:

Another posts