php – How do I implement Dependency Injection?

Question:

Goal: Get something like this (pseudocode):

class Validation
{
    private $db; 
    public function __construct(DB $db)
    {
        $this->db = $db;
    }
    public function checkUnique()
    {
        $this->db->countUsers();
    }
}

Conditional implementation:

class DB
{
    // переменные для подключения к БД:
    // protected: host, login, db, password

    public function __construct()
    {
        // Возвращение объекта подключения к БД DBConnect
    }

    public function checkDouble($table, $column, $email)
    {
        // тут мы сходили в базу
        return $table.'-'.$column.'-'.$email;
    }
}

class Validation
{
    public function checkUnique($table, $column, $email)
    {
        $count = (new DB())->checkDouble($table, $column, $email);
    }
}

$obj = new DB();
$val = new Validation();
$check = $val->checkUnique('users', 'mail', 'email@domain.com');

I don't really understand what to transfer to the Validation constructor in my case? There is no $ db variable in Validation, and you simply cannot pass the class, for example, public function __construct(DB) writes there must be a variable. How to do it right then?

Answer:

di is a tool for dependency injection; there are already quite a few of them with their own peculiarities, there is a little information in psr https://github.com/php-fig/container

Your answer is written in pseudo code.

class Validation
{
   private $db; 
   public function __construct(DB $db)
   {
       $this->db = $db;
   }
   public function checkUnique()
   {
    $this->db->countUsers();
   }
}


$validation = new Validation(new DB());
$validation->checkUnique();

// но обычно при использование DI есть объект реализующий ContainerInterface (пусть будет $container) и пишется примерно так
$validation = $container->get(Validator::class);
$validation->checkUnique();
// Это был пример service locator.

By the way, I have my own small project to implement the di tool https://github.com/smpl/mydi

There is also such a thing as DIP (Dependecy Injection Principle) and it is all based on aggregation and composition https://ru.wikipedia.org/wiki/%D0%90%D0%B3%D1%80%D0%B5% D0% B3% D0% B8% D1% 80% D0% BE% D0% B2% D0% B0% D0% BD% D0% B8% D0% B5 _ (% D0% BF% D1% 80% D0% BE% D0 % B3% D1% 80% D0% B0% D0% BC% D0% BC% D0% B8% D1% 80% D0% BE% D0% B2% D0% B0% D0% BD% D0% B8% D0% B5 )

Scroll to Top