實(shí)現(xiàn)了松耦合的軟件架構(gòu),可得到更好的測試,管理和擴(kuò)展的代碼
通過配置需要注入的依賴,Connection 能從 $config 中獲取到所有它需要的依賴。如果沒有依賴注入,Connection 會(huì)直接創(chuàng)建它需要的依賴,這樣不利于測試和擴(kuò)展 Connection。
許多框架已經(jīng)有用于DI的容器,這些容器通過配置數(shù)組創(chuàng)建對象,并在需要的地方(即在控制器中)注入它們。
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()); } }
更多建議: