Dependency Injection code examples of PHP design pattern (15)

purpose

Realize a loosely coupled software architecture, which can get better testing, management and extended code

Dependency injection mode: Dependency Injection is an implementation of Inversion of Control. To achieve the inversion of control, the usual solution is to delegate the creation of the callee instance to the IoC container, and then inject the callee into the caller (implemented by constructor/method injection), so that we can achieve The process of decoupling the caller and the callee is called dependency injection.

usage

DatabaseConfiguration is injected into DatabaseConnection and get the required $config. If there is no dependency injection mode, the configuration will directly create a DatabaseConnection. This is bad for testing and expansion.

example

  • Doctrine2 ORM uses dependency injection. For example, the configuration injected into the Connection object. For testing, you can easily create scalable simulation data and inject it into the Connection object.

  • Symfony and Zend Framework 2 already have dependency injection containers. They create objects through configured arrays and inject them where needed (in the controller).

UML graphics

★Official PHP advanced learning exchange community "click" management to organize some materials, BAT and other first-line companies have advanced knowledge systems (relevant learning materials and written interview questions) and are not limited to: distributed architecture, high scalability, high Performance, high concurrency, server performance tuning, TP6, laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripts, Docker, microservices, Nginx and other knowledge points, advanced advanced dry goods

Code

  • DatabaseConfiguration.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
    {
        // 这仅仅是演示,而不是一个真正的  DSN
        // 注意,这里只使用了注入的配置。 所以,
        // 这里是关键的分离关注点。

        return sprintf(
            '%s:%s@%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:1234@localhost:3306', $connection->getDsn());
    }
}

The Growth Path of PHP Internet Architect * The Ultimate Guide to "Design Patterns"

PHP Internet Architect 50K Growth Guide + Industry Problem Solving Guide (Continuous Update)

Interview with 10 companies, get 9 offers, PHP interview questions in 2020

★If you like my article and want to communicate and learn with more senior developers, get more technical consultation and guidance related to interviews with big factories, welcome to join our group, password: phpzh (Junyang number 856460874).

The latest PHP advanced tutorial in 2020, full series!

If the content is good, I hope everyone will support and encourage you to give a like/like, and welcome to communicate together; in addition, if you have any questions, you can suggest what you want to see in the comments.

Guess you like

Origin blog.csdn.net/weixin_43814458/article/details/108609650