>  기사  >  백엔드 개발  >  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); 
    }
}

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

를 사용하는 것은 일반적으로 싱글톤으로 설계되어야 하므로 여기서는 복잡하게 만들지 않겠습니다.

Dependency Insertion

분명히 데이터베이스 구성은 교체 가능한 부분이므로 빼내야 합니다.

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()); 
    }
}

이렇게 하면 구성 파일과 연결 로직의 분리가 완료됩니다.

Mysql을 주입하려면

$config = new MysqlConfiguration('127.0.0.1','root','','my_db',22);
$db = new Mysql($config);
$con = $db->connect();

$config를 사용하세요. 이를 종속성 주입이라고 합니다.

위 내용은 PHP 디자인 패턴 - 의존성 주입 사용법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.