Explain the dependency injection mode of PHP design pattern in detail

Time:2022-8-4

Purpose

Implements a loosely coupled software architecture for better testing, management and scaling of code

usage

The DatabaseConfiguration is injected into the DatabaseConnection and gets the required $config. Without dependency injection mode, the configuration will create the DatabaseConnection directly. This is bad for testing and scaling.

example

The Doctrine2 ORM uses dependency injection. For example, the configuration injected into the Connection object. For testing, extensible mock data can easily be created and injected into the Connection object.

Symfony and Zend Framework 2 already have dependency injection containers. They create objects from an array of configs and inject them where needed (in the controller).

UML diagram

CodeDatabaseConfiguration.php


<?php

namespace DesignPatterns\Structural\DependencyInjection;

class DatabaseConfiguration
{
    /**
     * @var string
     */
    private $host;

    /**
     * @var int
     */
    private $port;

    /**
     * @var string
     */
    private $username;

    /**
     * @var string
     */
    private $password;

    public function __construct(string $host, int $port, string $username, string $password)
    {
        $this->host = $host;
        $this->port = $port;
        $this->username = $username;
        $this->password = $password;
    }

    public function getHost(): string
    {
        return $this->host;
    }

    public function getPort(): int
    {
        return $this->port;
    }

    public function getUsername(): string
    {
        return $this->username;
    }

    public function getPassword(): string
    {
        return $this->password;
    }
}
?>

DatabaseConnection.php

<?php

namespace DesignPatterns\Structural\DependencyInjection;

class DatabaseConnection
{
    /**
     * @var DatabaseConfiguration
     */
    private $configuration;

    /**
     * @param DatabaseConfiguration $config
     */
    public function __construct(DatabaseConfiguration $config)
    {
        $this->configuration = $config;
    }

    public function getDsn(): string
    {
        // This is just a demo, not a real DSN
        // Note that only the injected configuration is used here. so,
        // Here is the key separation of concerns.

        return sprintf(
            '%s:%[email protected]%s:%d',
            $this->configuration->getUsername(),
            $this->configuration->getPassword(),
            $this->configuration->getHost(),
            $this->configuration->getPort()
        );
    }
}
?>

Test Tests/DependencyInjectionTest.php


<?php

namespace DesignPatterns\Structural\DependencyInjection\Tests;

use DesignPatterns\Structural\DependencyInjection\DatabaseConfiguration;
use DesignPatterns\Structural\DependencyInjection\DatabaseConnection;
use PHPUnit\Framework\TestCase;

class DependencyInjectionTest extends TestCase
{
    public function testDependencyInjection()
    {
        $config = new DatabaseConfiguration('localhost', 3306, 'domnikl', '1234');
        $connection = new DatabaseConnection($config);

        $this->assertEquals('domnikl:[email protected]:3306', $connection->getDsn());
    }
}
?>

The above is the detailed content of the dependency injection mode of the PHP design mode. For more information about the dependency injection mode of the PHP design mode, please pay attention to other related articles on developpaer!

Recommended Today

Please use id instead of name when implementing anchors in HTML5

HTML5 has removed the name attribute, please use id when implementing the anchor point, example effect: http://keleyi.com/keleyi/phtml/html5/9.htm Support Chrome, Firefox, IE8 and above browsers. Here is the complete code: copy code code show as below: <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml”> <head> <title>HTML5 Anchor Example–Ke Leyi</title><base target=”_blank” /><style> body{margin:0px;} </style> </head> […]