diff --git a/demo/Structural/DependencyInjection/DatabaseConfiguration.php b/demo/Structural/DependencyInjection/DatabaseConfiguration.php new file mode 100644 index 0000000..8d924be --- /dev/null +++ b/demo/Structural/DependencyInjection/DatabaseConfiguration.php @@ -0,0 +1,57 @@ +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; + } +} \ No newline at end of file diff --git a/demo/Structural/DependencyInjection/DatabaseConnection.php b/demo/Structural/DependencyInjection/DatabaseConnection.php new file mode 100644 index 0000000..14bb7bb --- /dev/null +++ b/demo/Structural/DependencyInjection/DatabaseConnection.php @@ -0,0 +1,41 @@ +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() + ); + } +} \ No newline at end of file diff --git a/demo/Structural/DependencyInjection/Run.php b/demo/Structural/DependencyInjection/Run.php new file mode 100644 index 0000000..82ab5ee --- /dev/null +++ b/demo/Structural/DependencyInjection/Run.php @@ -0,0 +1,45 @@ +getDsn()); + } +} \ No newline at end of file diff --git a/demo/Structural/DependencyInjection/Tests/DependencyInjectionTest.php b/demo/Structural/DependencyInjection/Tests/DependencyInjectionTest.php new file mode 100644 index 0000000..0b8965f --- /dev/null +++ b/demo/Structural/DependencyInjection/Tests/DependencyInjectionTest.php @@ -0,0 +1,17 @@ +assertEquals('domnikl:1234@localhost:3306', $connection->getDsn()); + } +} \ No newline at end of file