2017-02-14 1 views
0

mysqli 래퍼 구현과 관련하여 PHP 싱글 톤 패턴에 문제가 있습니다. mysqli 래퍼 용 ​​PHP 싱글 톤 패턴

class DbHandler 
{ 

    private $mysqli; 
    private $query; 
    private $results = array(); 
    private $numRows = 0; 

    public static $instance; 

    public static function getInstance() { 
     if (!isset(self::$instance)) { 
      self::$instance = new DbHandler; 
     } 
     return self::$instance; 
    } 

    public function __construct() { 
     $this->mysqli = new mysqli("127.0.0.1", "root", "", "improved_portal"); 
     if ($this->mysqli->connect_error) { 
      die($this->mysqli->connect_error); 
     } 
    } 

    public function query($statement) { 
     if ($this->query = $this->mysqli->query($statement)) { 
      foreach ($this->query as $value) { 
       $this->results[] = $value; 
      } 
      $this->numRows = $this->query->num_rows; 
      return $this; 
     } 
    } 

    public function getResults() { 
     return $this->results; 
    } 

    public function getNumRows() { 
     return $this->numRows; 
    } 

} 

내가 다른 객체의 클래스를 활용하는 이동

, 나는 결과에 문제가있는 것 같다. 고유 한 $ 결과로 매번 새 오브젝트를 작성하는 대신 초기 오브젝트의 사본을 작성하는 것 같습니다. 예를 들어 ...

$object1 = DbHandler::getInstance(); 
$object1->query("SELECT * FROM table_a")->getResults(); 

$object2 = DbHandler::getInstance(); 
$object2->query("SELECT * FROM table_b")->getResults(); 

$ object2에는 두 검색어의 결과가 포함되어 있습니다. 이는 분명히 내가 기대하는 바가 아닙니다. 쿼리 함수는 두 번째 쿼리의 결과를 명확하게 반복하고이를 첫 번째 개체의 $ results 속성에 추가합니다. 각 개체에 고유 한 속성이 포함되도록 DbHandler 클래스의 새 인스턴스를 어떻게 호출해야합니까?

+0

: 기능과 같이 다시 작성해야합니다. –

+0

'$ this-> results'는 매회 __cleared__해야합니다. –

답변

0

우선 - 이것은 싱글 톤 패턴이 아닙니다. 당신의 __construct 공용이기 때문에 나는이 작업을 수행 할 수 있습니다

$conn1 = new DbHandler(); 
$conn2 = new DbHandler(); 
$conn3 = new DbHandler(); 

는이를 방지하기 위해 - __construct은/개인 보호해야합니다.

두 번째 - 동일한 객체에서 query()을 호출 할 때마다이 함수는 결과를 results 속성에 추가합니다. 그리고이 results 속성은 지우지 않고 모든 쿼리에 사용됩니다. 확실히 이전의 모든 값을 유지합니다. 당신은 당신의`__construct()`방식과 개인`$ instance` 속성을하고 만 개체를 ​​만드는 클래스의 정적`의 getInstance()`방법을 사용해야합니다

public function query($statement) { 
    // clear result from previous function call 
    $this->results = array(); 

    if ($this->query = $this->mysqli->query($statement)) { 
     foreach ($this->query as $value) { 
      $this->results[] = $value; 
     } 
     $this->numRows = $this->query->num_rows; 
     return $this; 
    } 
}