PHP 依賴注入模式

2022-03-21 18:05 更新

目的

實(shí)現(xiàn)了松耦合的軟件架構(gòu),可得到更好的測試,管理和擴(kuò)展的代碼

用例

通過配置需要注入的依賴,Connection 能從 $config 中獲取到所有它需要的依賴。如果沒有依賴注入,Connection 會(huì)直接創(chuàng)建它需要的依賴,這樣不利于測試和擴(kuò)展 Connection。

例子

  • Doctrine2 ORM 使用了依賴注入,它通過配置注入了 Connection 對象。為了達(dá)到方便測試的目的,可以很容易的通過配置創(chuàng)建一個(gè)mock的 Connection 對象。
  • 許多框架已經(jīng)有用于DI的容器,這些容器通過配置數(shù)組創(chuàng)建對象,并在需要的地方(即在控制器中)注入它們。

UML 圖

Alt DependencyInjection UML Diagram

代碼

DatabaseConfiguration.php

<?php

declare(strict_types=1);

namespace DesignPatterns\Structural\DependencyInjection;

class DatabaseConfiguration
{
    public function __construct(
        private string $host,
        private int $port,
        private string $username,
        private string $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

declare(strict_types=1);

namespace DesignPatterns\Structural\DependencyInjection;

class DatabaseConnection
{
    public function __construct(private DatabaseConfiguration $configuration)
    {
    }

    public function getDsn(): string
    {
        // this is just for the sake of demonstration, not a real DSN
        // notice that only the injected config is used here, so there is
        // a real separation of concerns here

        return sprintf(
            '%s:%s@%s:%d',
            $this->configuration->getUsername(),
            $this->configuration->getPassword(),
            $this->configuration->getHost(),
            $this->configuration->getPort()
        );
    }
}

測試

Tests/DependencyInjectionTest.php

<?php

declare(strict_types=1);

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->assertSame('domnikl:1234@localhost:3306', $connection->getDsn());
    }
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號