2014-08-02 1 views
1

저는 최근에 동적 PDO 연결 방법을 사용해 왔습니다. 그러나 다른 클래스를 사용할 때 몇 가지 문제가 발생합니다.다른 클래스에서 생성 된 연결 방법을 사용하면 작동하지 않습니다.

서버 클래스에서 생성 된 메서드를 사용하여 Admin 클래스의 데이터베이스에 연결할 수없는 이유는 무엇입니까?

많은 솔루션을 사용해 보았습니다. 이 하나가 내게 가장 논리적 인 것 같았습니다 ...

모든 클래스에서 연결을 만들 필요가 없도록 어떻게 작동합니까?

class Server 
{ 
    private $hostdb = 'blah'; 
    private $namedb = 'blah'; 
    private $userdb = 'blah'; 
    private $passdb = 'blah'; 

    public static $conn; 

    public $errorMessage = 'If you read this text, contact web administrator and tell him about your problem.'; 

    public function __construct() 
    { 
     $this->connect(); 
    } 

    public function connect() 
    { 
     try { 
      $this->conn = new PDO("mysql:host=$this->hostdb; dbname=$this->namedb", $this->userdb, $this->passdb, array(PDO::ATTR_PERSISTENT => true)); 
      $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
      $this->conn->exec("SET CHARACTER SET utf8"); 

     } catch (PDOException $e) { 
      echo 'Connection failed: ' . $e->getMessage(); 
     } 
    } 
} 

그리고 관리 클래스 :

내가 config.req.php 파일에서 두 서버, 사용자 및 관리자 클래스를 인스턴스화 한
class Admin extends User 
{ 

    function someFunction($table) 
    { 
     try { 
      $sql = "SELECT * FROM $table"; 

      //I want to change this line so that my connection would work 
      $result = Server::$conn->query($sql); 

         while ($row = $result->fetch(PDO::FETCH_NUM)) { 
          //Do something 
         } 
        } catch (PDOException $e) { 
      //Show when debugging 
      //echo $e->getMessage(); 
      echo Server::errorMessage; 
     } 
    } 
} 

.

"Server :: $ conn->"를 "static :: $ conn->"으로 변경했을 때 여전히 오류가 발생했습니다.

답변

0

요청에 적어도 한번 인스턴스화 된 서버를 가지고 있는지 확인하십시오. 그렇지 않으면 connect()이 호출되지 않습니다. 또한 $this->conn은 새 public 인스턴스 속성을 만듭니다. Static properties need to be set with static::$conn or self::$conn.

그래서 보조 노트에

public function connect() 
{ 
    try { 
     self::$conn = new PDO("arguments …")); 
     self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     self::$conn->exec("SET CHARACTER SET utf8"); 
     // … shortened for brevity 

connect() 방법을 변경, 왜 그냥 Dependency Injection를 사용할 수 있습니까? 이는 유지 보수가 용이하고 테스트 가능한 디자인을 만듭니다. $this->conn를 유지하고

class Server 
{ 
    private $hostdb = 'blah'; 
    private $namedb = 'blah'; 
    private $userdb = 'blah'; 
    private $passdb = 'blah'; 

    private $conn; 

    public function getConnection() 
    { 
     if (!isset($this->conn)) { 
      $this->connect(); 
     } 

     return $this->connection; 
    } 

처럼 뭔가를 (생성자에 추가) 대신 모든 정적 물건을 제거하고 사용자의 관리 클래스 : 또 다른 측면 노트에

class Admin extends User 
{ 
    private $server; 

    public function __construct(Server $server) 
    { 
     $this->server = $server; 
    } 

    function someFunction($table) 
    { 
     try { 
      $sql = "SELECT * FROM $table"; 
      $result = $this->server->getConnection()->query($sql); 

:

$sql = "SELECT * FROM $table" 

문자열을 쿼리에 삽입하면 SQL Injection attacks을 열 수 있습니다. 대신 준비된 문을 사용하십시오.

+0

놀라운 소식입니다. 고마워. :) –

관련 문제