2017-02-14 4 views
0

PHPシングルトンパターンに問題があります。具体的には、mysqliラッパーの実装に関してです。私は他のオブジェクトにクラスを利用するために行くとき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は、明らかに私が期待していないものです。クエリ関数は、2番目のクエリの結果を明確にループし、最初のオブジェクトの$ resultsプロパティに追加します。各オブジェクトに固有のプロパティが含まれるように、DbHandlerクラスの新しいインスタンスをどのように呼び出す必要がありますか?

+0

:機能は次のように書き直す必要があります。 –

+0

毎回 '$ this-> results'を__cleared__する必要があります –

答えて

0

まずは - これはシングルトンパターンではありません。あなた__constructが公開されているように私はこれを行うことができます。

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

はこれを防ぐために - __constructは、プライベート/保護されなければなりません。

第2回 - 同じオブジェクトから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; 
    } 
}