ホームページ  >  記事  >  バックエンド開発  >  PHP デザインパターン - 依存関係注入の使用方法の詳細な説明

PHP デザインパターン - 依存関係注入の使用方法の詳細な説明

黄舟
黄舟オリジナル
2017-07-17 16:01:131366ブラウズ

前書き

最後に、この有名なデザイン原則について話しましょう。実際、これは他のデザインパターンよりも簡単です。
依存性注入の本質は、クラスの交換不可能な部分を交換可能な部分から分離し、それらを注入を通じて使用して分離の目的を達成することです。

これはデータベースリンクの例です。皆さんも理解していただければ幸いです。

データベース接続クラス

class Mysql{
    private $host;
    private $port;
    private $username;
    private $password;
    private $db_name;
    public function construct(){
        $this->host = '127.0.0.1';
        $this->port = 22;
        $this->username = 'root';
        $this->password = '';
        $this->db_name = 'my_db';
    }
    public function connect(){
        return mysqli_connect($this->host,$this->username ,$this->password,$this->db_name,$this->port); 
    }
}

の使用は通常シングルトンとして設計されるべきなので、ここでは複雑にしません。

Dependency Injection

明らかに、データベース構成は交換可能な部分なので、取り外す必要があります。

$db = new Mysql();
$con = $db->connect();

そして、置き換えられない部分は次のようになります:

class MysqlConfiguration
{
    private $host;
    private $port;
    private $username;
    private $password;
    private $db_name;
    public function construct(string $host, int $port, string $username, string $password,string $db_name)
    {
        $this->host = $host;
        $this->port = $port;
        $this->username = $username;
        $this->password = $password;
        $this->db_name = $db_name;
    }
    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;
    }
    public function getDbName(): string
    {
        return $this->db_name;
    }
}

これで、

設定ファイル

と接続ロジックの分離が完了しました。

class Mysql
{
    private $configuration;
    public function construct(DatabaseConfiguration $config)
    {
        $this->configuration = $config;
    }
    public function connect(){
        return mysqli_connect($this->configuration->getHost(),$this->configuration->getUsername() ,
        $this->configuration->getPassword,$this->configuration->getDbName(),$this->configuration->getPort()); 
    }
}

$config を使用して Mysql を注入します。これは依存関係注入と呼ばれます。

以上がPHP デザインパターン - 依存関係注入の使用方法の詳細な説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。