From 31d3ff4aa4ff2b3fb18142bb8b2d6b1be09f8c5b Mon Sep 17 00:00:00 2001 From: cloud Date: Fri, 15 Apr 2022 04:28:30 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BE=9D=E8=B5=96=E6=B3=A8=E5=85=A5=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DatabaseConfiguration.php | 57 +++++++++++++++++++ .../DatabaseConnection.php | 41 +++++++++++++ demo/Structural/DependencyInjection/Run.php | 45 +++++++++++++++ .../Tests/DependencyInjectionTest.php | 17 ++++++ 4 files changed, 160 insertions(+) create mode 100644 demo/Structural/DependencyInjection/DatabaseConfiguration.php create mode 100644 demo/Structural/DependencyInjection/DatabaseConnection.php create mode 100644 demo/Structural/DependencyInjection/Run.php create mode 100644 demo/Structural/DependencyInjection/Tests/DependencyInjectionTest.php 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