2012-09-27 4 views
0

메인 포럼 클래스, 포럼 보드 클래스 및 스레드 클래스에 대한 많은 양의 클래스가 있습니다. 이들은 내 웹 사이트의 컨텍스트에서 모델로 생각할 수 있습니다.다른 모든 클래스에 대해 데이터베이스 클래스를 구현하려면 어떻게해야합니까?

이전 웹 개발자가 사용했던 설정은이 클래스 각각에 새로운 mysqli 연결을 만들고 클래스의 인스턴스 생성시 연결합니다. 즉, 스레드 페이지에는 포럼, 스레드 및 사용자를위한 3 개의 서로 다른 연결이 있습니다. 이것은 분명히 이상적이지 않으며 나는 심지어 최적이라고 생각하지 않습니다.

이전 프로젝트에서 데이터베이스 클래스의 새 인스턴스를 사용하고 있던 클래스에 전달할 수 있었지만 여러 클래스를 인스턴스화하고 데이터베이스 인스턴스를 전달해야하므로 이상적이지 않습니다. 각 반은 목적을 이길 것이다.

이러한 각 클래스에서 데이터베이스 호출은 각 클래스 내에서 데이터베이스 개체/인스턴스가 필요하므로 3 번 이상 별도 인스턴스를 인스턴스화 할 필요가 없습니다.

예를 들어, 스레드 클래스에서 당신은 할 수 :

function get_threads($board_id) { 
    return $this->con->query("some query"); 
} 

사람이 내가 이것을 달성 대해 갈 수있는 방법을 알고 있나요?

답변

3

필자는 공장 패턴에서와 같이 데이터를 얻을 수있는 데이터베이스 컨트롤러를 선호합니다. 아래 예제에서는 하나의 컨트롤러를 생성하고 구성 요소가 필요할 때 사용하도록 할 수 있습니다.

ex: $threads = new ThreadClass($mysqlConnection); 

나는이

# 1. mysql source or "socket" using PDO 
class SimpleDatabaseSocket { 

    protected static $dbh = false; 

    public function connect($database, $user, $pass, $host) { 
     $dsn = "mysql:dbname={$database};host={$host}"; 
     self::$dbh = new PDO($dsn, $user, $pass); 
     self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    } 

} 

# 2. always use an interface which defines required logic 
interface SimpleDatabaseInterface { 

    public function onRunQuery($query); 
} 

# 3. create the accessible controller for inherited & ancillary logic 
class SimpleDatabaseController extends SimpleDatabaseSocket implements SimpleDatabaseInterface { 

    private $host = ""; 
    private $base = ""; 
    private $usr = ""; 
    private $pwd = ""; 
    private $table = ""; 

    # when we create the controller, you MUST pass the connection params 
    public function __construct($host, $usr, $pwd, $base) { 
     $this->setUsr($usr); 
     $this->setPwd($pwd); 
     $this->setBase($base); 
     $this->setHost($host); 
    } 

    # mysql host/ip 
    public function setHost($host) { 
     $this->host = $host; 
    } 

    # mysql database 
    public function setBase($base) { 
     $this->base = $base; 
    } 

    # mysql username 
    public function setUsr($usr) { 
     $this->usr = $usr; 
    } 

    # mysql password 
    public function setPwd($pwd) { 
     $this->pwd = $pwd; 
    } 
    # allow this controller to switch tables dynamically. 
    public function onChangeTable($table) { 
     $this->table = $table; 
    } 

    # connect to the database 
    protected function onConnect() { 
     $this->connect($this->base, $this->usr, $this->pwd, $this->host); 
    } 

    # connects to the DB and runs a custom query 
    public function onRunQuery($query) { 
     try { 
      if (!self::$dbh) 
       $this->onConnect(); 
      $result = self::$dbh->query($query); 
      $out = $result->fetchAll(PDO::FETCH_ASSOC); 
     } catch (PDOException $e) { 

     } 
     return $out; 
    } 

} 

# exmaple usage 
$mysql = new SimpleDatabaseController("HOSTNAME","USERNAME","PASSWORD","DATABASE"); 
$result = $mysql->onRunQuery("SELECT * FROM TABLE LIMIT 0,2"); 
print("<pre>" . print_r($result, true) . "</pre>"); 
+0

우수 대답 도움이되기를 바랍니다. – FunctionR

관련 문제