依赖注入模式

This commit is contained in:
cloud 2022-04-15 04:28:30 +08:00
parent 1b5fe57b9f
commit 31d3ff4aa4
4 changed files with 160 additions and 0 deletions

View File

@ -0,0 +1,57 @@
<?php
namespace demo\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;
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace demo\Structural\DependencyInjection;
/**
* 数据库连接
*/
class DatabaseConnection
{
/**
* @var DatabaseConfiguration
*/
private $configuration;
/**
* @param DatabaseConfiguration $config
*/
public function __construct(DatabaseConfiguration $config)
{
$this->configuration = $config;
}
public function getDsn() : string
{
// 这仅仅是演示,而不是一个真正的 DSN
// 注意,这里只使用了注入的配置。 所以,
// 这里是关键的分离关注点。
// 将获取的信息 按照 %s:%s@%s:%d 拼装成字符串
// 格式化字符串
return sprintf(
'%s:%s@%s:%d',
$this->configuration->getUsername(),
$this->configuration->getPassword(),
$this->configuration->getHost(),
$this->configuration->getPort()
);
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace demo\Structural\DependencyInjection;
class Run extends \bin\Design
{
/**
* 用松散耦合的方式来更好的实现可测试、可维护和可扩展的代码。
*
* 依赖注入模式依赖注入Dependency Injection是控制反转Inversion of Control的一种实现方式。
* 要实现控制反转,通常的解决方案是将创建被调用者实例的工作交由 IoC 容器来完成,然后在调用者中注入被调用者(通过构造器 / 方法注入实现),
* 这样我们就实现了调用者与被调用者的解耦,该过程被称为依赖注入。
*
* DatabaseConfiguration 被注入 DatabaseConnection 并获取所需的 $config
* 如果没有依赖注入模式, 配置将直接创建 DatabaseConnection 。这对测试和扩展来说很不好。
*
* @inheritDoc
*/
public function setDesignName() : string
{
return '依赖注入模式Dependency Injection';
}
/**
* @inheritDoc
*/
public function setDesignRefUrl() : string
{
return 'https://learnku.com/docs/php-design-patterns/2018/DependencyInjection/1501';
}
/**
* @inheritDoc
*/
public function main()
{
// 设置配置信息
$config = new DatabaseConfiguration('localhost', 3306, 'domnikl', '1234');
// 格式化配置信息
$connection = new DatabaseConnection($config);
dump($connection->getDsn());
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace demo\Structural\DependencyInjection\Tests;
use demo\Structural\DependencyInjection\DatabaseConfiguration;
use demo\Structural\DependencyInjection\DatabaseConnection;
class DependencyInjectionTest extends \PHPUnit\Framework\TestCase
{
public function testDependencyInjection()
{
$config = new DatabaseConfiguration('localhost', 3306, 'domnikl', '1234');
$connection = new DatabaseConnection($config);
$this->assertEquals('domnikl:1234@localhost:3306', $connection->getDsn());
}
}