41 lines
974 B
PHP
41 lines
974 B
PHP
<?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()
|
|
);
|
|
}
|
|
} |