K
K
kot-airplane2017-08-26 20:18:32
PHP
kot-airplane, 2017-08-26 20:18:32

Is DI implemented correctly?

Introductory: the class that implements the methods of working with the database and the class that needs the database are not connected in any way (not successors).
Purpose:
1) so that the class that needs the database can use it without explicitly transferring the database to it each time
2) The connection parameters are taken out of the database class.
The code:

class Config
{
    public $host = 'localhost';
    public $db =   'loadbot_db'; 
    public $charset = 'utf8';
    public $user = 'user';      
    public $pass = 'qwerty'; 
}

class DB
{
    public function __construct(Config $config) {
        // тут происходит подключение к БД
    }
    // тут все остальные методы работы с БД
}

class NeedDB
{
    public $db;
    
    public function __construct() {
        $cache = new Config();
        $this->db = new DB($cache);
    }
}

$var = new NeedDB();

Is it implemented correctly, are there any shortcomings, can it be improved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
index0h, 2017-08-26
@kot-airplane

1. Do not use public properties
2. It makes sense to use constants to describe parameters

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question