2013-10-05 3 views
1

좋아요, 알았어요, 나는 스 니펫 벨로우즈가 나의 최종 목표라고 말함으로써 시작해야한다고 생각합니다. 내 응용 프로그램에서이 어디서나 같은 줄을 실행할 수 있기를 원하고는 PDO 연결 및 실행을 처리해야 :어떻게하면 PDO 연결을보다 효율적으로 만들 수 있습니까?

Database::query('QUERY');

이 작업을 수행하기 위해, 나는 백그라운드에서 실행되는 두 개의 파일을 다음했다.

Connection.php : PDO 연결을 처리합니다.

class Connection { 

    /** 
    * The PDO connection. 
    * 
    * @var PDO 
    */ 
    protected $pdo = NULL; 

    /** 
    * The type of database we're connection to. 
    * 
    * @var string 
    */ 
    protected $type = ''; 

    /** 
    * The name of the connected database. 
    * 
    * @var string 
    */ 
    protected $database = ''; 

    /** 
    * The database connection details. 
    * 
    * @var array 
    */ 
    protected $config = array(); 

    /** 
    * Create the connection instance. 
    * 
    */ 
    public function __construct() 
    { 
     // Import the configuration information from database.php 
     $this->config = Config::load('database'); 

     // Pull the database type 
     $this->type = $this->config['database']; 

     // Pull the database name 
     if(isset($this->config[$this->type]['database'])) 
     { 
      $this->database = $this->config[$this->type]['database']; 
     } 

     // Check to see if a connection has been made or not 
     if($this->pdo==NULL) 
     { 
      // Create the connection 
      $this->pdo = $this->createConnection(); 
     } 
    } 

    /** 
    * Query the database. 
    * 
    * @param string $query 
    * @return array 
    */ 
    public function query($query) 
    { 
     // Check to see if we have a connection 
     if($this->pdo!=NULL) 
     { 
      // Execute the raw query 
      $query = $this->pdo->query($query); 

      return $query; 
     } 

     return false; 
    } 

    /** 
    * Execute a query on the database. 
    * 
    * @param string $query 
    * @return int 
    */ 
    public function exec($query) 
    { 
     // Check to see if we have a connection 
     if($this->pdo!=NULL) 
     { 
      // Execute the raw query 
      $execution = $this->pdo->exec($query); 

      return $execution; 
     } 

     return false; 
    } 

    /** 
    * Execute a query and return the last inserted Id 
    * 
    * @param string $query 
    * @return int 
    */ 
    public function execLastId($query) 
    { 
     // Check to see if we have a connection 
     if($this->pdo!=NULL) 
     { 
      // Execute the query and return the Id 
      if($this->exec($query)) 
      { 
       return $this->pdo->lastInsertId(); 
      } 
     } 

     return false; 
    } 

    /** 
    * Prepare and execute against the database. 
    * 
    * @param string $query 
    * @param array $params 
    * @return array 
    */ 
    public function prepare($query, $params) 
    { 
     // Check to see if we have a connection 
     if($this->pdo!=NULL) 
     { 
      // Prepare the query 
      $query = $this->pdo->prepare($query); 

      // Execute the query 
      $query->execute($params); 

      return $query->fetchAll(); 
     } 

     return false; 
    } 

    /** 
    * Create a new PDO connection. 
    * 
    * @return PDO 
    */ 
    protected function createConnection() 
    { 
     // See if we can attempt to make a connection 
     if(isset($this->config[$this->type])) 
     { 
      $hasDSN = false; 

      // Decide what DSN to use 
      if($this->type=='mysql') 
      { 
       $hasDSN = true; 

       $dsn = $this->getMySQLDSN(); 
      } 

      // If a DSN has been found, make the connection 
      if($hasDSN) 
      { 
       $username = $this->config[$this->type]['username']; 
       $password = $this->config[$this->type]['password']; 

       return new PDO($dsn, $username, $password); 
      } 
     } 

     return NULL; 
    } 

    /** 
    * Get the MySQL DSN. 
    * 
    * @return string 
    */ 
    protected function getMySQLDSN() 
    { 
     return 'mysql:host='.$this->config['mysql']['hostname'].';dbname='.$this->database; 
    } 

} 

Database.php : 연결 사이의 중개자입니다.

class Database { 

    /** 
    * Run a raw query on the database. 
    * 
    * @param string $query 
    * @return array 
    */ 
    public static function query($query) 
    { 
     // Create the connection 
     $conn = new Connection; 

     // Return the query 
     return $conn->query($query); 
    } 

    /** 
    * Execute a query on the database. 
    * 
    * @param string $query 
    * @return int 
    */ 
    public static function exec($query) 
    { 
     // Create the connection 
     $conn = new Connection; 

     // Return the query 
     return $conn->exec($query); 
    } 

    /** 
    * Execute a query and return the last inserted Id 
    * 
    * @param string $query 
    * @return int 
    */ 
    public static function execLastId($query) 
    { 
     // Create the connection 
     $conn = new Connection; 

     // Return the query 
     return $conn->execLastId($query); 
    } 

    /** 
    * Prepare and then execute a query. 
    * 
    * @param string $query 
    * @param array $params 
    * @return array 
    */ 
    public static function prepare($query, array $params) 
    { 
     // Create the connection 
     $conn = new Connection; 

     // Return the query 
     return $conn->prepare($query, $params); 
    } 
} 

내 질문에 : 이것이 효율적입니까? 더 간단한 방법이 있습니까? 나는 어떤 지침을 주셔서 감사합니다. 저는 제 자신을 초보자라고 생각하지만 응용 프로그램이 효율적이고 자신의 체중이 줄어들지 않도록하는 경험이 정말 부족합니다.

+0

읽기 :

그래서 작은 변화 당신은 당신의 데이터베이스 클래스를 처음 사용할 때 연결을 만들 수 있습니다) – deceze

답변

1

이것은 효율적이지 않습니다. 쿼리를 실행할 때마다 새로운 Connection 객체가 만들어지고 새로운 PDO 연결이 생성됩니다. 데이터베이스에 연결하면 약간의 오버 헤드가 발생합니다. 실제로는 매번 연결할 필요가 없습니다. 한 번 연결하면 후속 쿼리에 대한 연결을 사용할 수 있습니다. (http://kunststube.net/static/ [정역학을 사용하여 귀하의 테스트 용이성을 죽이지 방법]

class Database { 

    /** 
    * Reference to the connection 
    */ 
    private static $connection = null; 

    /** 
    * Run a raw query on the database. 
    * 
    * @param string $query 
    * @return array 
    */ 
    public static function query($query) 
    { 
     // Get the connection 
     $conn = self::getConnection(); 

     // Return the query 
     return $conn->query($query); 
    } 

    public static function getConnection() 
    { 
     // Create the connection if needed. 
     if (self::$connection === null) 
     { 
     self::$connection = new Connection; 
     } 
     // Return new or existing instance. 
     return self::$connection; 
    } 

    ... 
+0

이것은 또한 $ database-> query ('QUERY');를 사용할 것임을 의미합니다. Database :: query ('QUERY') 대신; –

+0

아니요. 여전히 정적입니다. 나는 이것이 그 자체로 최선의 해결책은 아니라고 생각하지만, 그것은 또 다른 토론입니다. 그래서 나는 지금 거기에 가고 싶지 않았습니다. :) – GolezTrol

+0

이것은 정말로 흥미 롭습니다. 빠른 답장을 보내 주셔서 감사합니다. 나는 그것을 지금 시도 할 것이다! – kschembri

관련 문제