簡體   English   中英

我應該繼續在PHP中重新連接到mysql嗎?

[英]Should I keep reconnecting to mysql in PHP?

我有一個非常大的網站,每個頁面都是由幾個包含的文件構建的,我的網站是100%的過程格式,我正在嘗試學習在PHP中使用類和更多的OOP方法。

目前我的網站有一個包含在每個頁面中的頭文件,在這個頭文件中是一個mysql連接,並且是頁面的持續時間,所以如果我需要從不同的文件運行10個不同的查詢,它們都運行而不需要建立新連接,因此連接只進行一次。

現在我正在嘗試轉換為更多的OO方式,我開始編寫一個mysql類來連接和運行查詢,所以我正在考慮使用類__construct函數來建立與mysql的連接,我只是好奇這是怎么回事雖然可以工作,但每次調用該類時,它都會創建或嘗試與mysql建立連接而不是僅僅一次。

也許我沒有清楚地思考它。 我應該只在標題中啟動此課程一次,然后我不再需要擔心嗎?

您可以創建MySQL類的單個全局對象,並在任何地方使用該對象。 那么你的構造函數只會被調用一次。

或者你可以在任何地方創建MySQL類的新對象。 如果已經有一個打開, mysql_connect不會打開新連接:

如果使用相同的參數對mysql_connect()進行第二次調用,則不會建立新的鏈接,而是返回已打開的鏈接的鏈接標識符。

我認為最好的方法是使用一個特殊的類來處理mysql連接並將其用作單例。 使構造函數成為私有的,並使其返回現有連接或新連接的實例。

這是我的例子:

class db 
{

    public $host;
    public $user;
    public $pass;
    public $database;

    private static $instance = false;

    private function __construct() 
    {

    }

    public static function getInstance()
    {
        if (self::$instance === false)
        {
            self::$instance = new db;
        }
        return self::$instance;
    }

        public function db_connect()
        {
        }

        public function db_disconnect()
        {
        }
}

這樣,無論何時調用:db :: getInstance() - > db_connect(),您都可以確定到處都只有該連接的一個實例。

是的,你不應該連接多次。 一直打開和關閉連接的開銷大於在腳本運行的相對較短的時間內保持打開的開銷。 因此,您應該在開始時創建該類的實例,並將其保存在全局變量中。

將自己的類編寫為練習當然不是一個壞主意,但也許你應該研究一下現有的數據庫連接管理解決方案(Zend_Db等)。

您始終可以將數據庫鏈接引用存儲在STATIC類變量中,並在需要時調用它。 但是,PHP本身會嘗試使用現有鏈接(如果它存在於內存中)。

我有一個示例數據庫處理程序代碼,當然是PHP 5並使用PDO。

<?php
// Class providing generic data access functionality
class DatabaseHandler
{
  // Hold an instance of the PDO class
  private static $_mHandler;

  // Private constructor to prevent direct creation of object
  private function __construct()
  {
  }

  // Return an initialized database handler 
  private static function GetHandler()
  {
    // Create a database connection only if one doesn’t already exist
    if (!isset(self::$_mHandler))
    {
      // Execute code catching potential exceptions
      try
      {
        // Create a new PDO class instance
        self::$_mHandler =
          new PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD);

        // Configure PDO to throw exceptions
        self::$_mHandler->setAttribute(PDO::ATTR_ERRMODE,
                                       PDO::ERRMODE_EXCEPTION);
        self::$_mHandler->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
      }
      catch (PDOException $e)
      {
        // Close the database handler and trigger an error
        self::Close();
        trigger_error($e->getMessage(), E_USER_ERROR);
      }
    }

    // Return the database handler
    return self::$_mHandler;
  }
  // Clear the PDO class instance
  public static function Close()
  {
    self::$_mHandler = null;
  }
  // Wrapper method for PDO::prepare
  private static function Prepare($queryString)
  {
    // Execute code catching potential exceptions
    try
    {
      // Get the database handler and prepare the query
      $database_handler = self::GetHandler();
      $statement_handler = $database_handler->prepare($queryString);

      // Return the prepared statement
      return $statement_handler;
    }
    catch (PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }
  }

  // Wrapper method for PDOStatement::execute()
  public static function Execute($sqlQuery, $params = null)
  {
    // Try to execute an SQL query or a stored procedure
    try
    {
        $statement_handler = self::Prepare($sqlQuery);

      // Execute query
      $statement_handler->execute($params);
    }
    // Trigger an error if an exception was thrown when executing the SQL query
    catch(PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }
  }

  // Wrapper method for PDOStatement::fetchAll()
  public static function GetAll($sqlQuery, $params = null,
                                $fetchStyle = PDO::FETCH_ASSOC)
  {
    // Initialize the return value to null
    $result = null;

    // Try to execute an SQL query or a stored procedure
    try
    {
        $statement_handler = self::Prepare($sqlQuery);

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

      // Fetch result
      $result = $statement_handler->fetchAll($fetchStyle);
    }
    // Trigger an error if an exception was thrown when executing the SQL query
    catch(PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }

    // Return the query results
    return $result;
  }

  // Wrapper method for PDOStatement::fetch()
  public static function GetRow($sqlQuery, $params = null,
                                $fetchStyle = PDO::FETCH_ASSOC)
  {
    // Initialize the return value to null
    $result = null;

    // Try to execute an SQL query or a stored procedure
    try
    {

      $statement_handler = self::Prepare($sqlQuery);

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

      // Fetch result
      $result = $statement_handler->fetch($fetchStyle);
    }
    // Trigger an error if an exception was thrown when executing the SQL query
    catch(PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }

    // Return the query results
    return $result;
  }

  // Return the first column value from a row
  public static function GetOne($sqlQuery, $params = null)
  {
    // Initialize the return value to null    
    $result = null;

    // Try to execute an SQL query or a stored procedure
    try
    {
        $statement_handler = self::Prepare($sqlQuery);

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

      // Fetch result
      $result = $statement_handler->fetch(PDO::FETCH_NUM);

      /* Save the first value of the result set (first column of the first row)
         to $result */
      $result = $result[0];
    }
    // Trigger an error if an exception was thrown when executing the SQL query
    catch(PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }

    // Return the query results
    return $result;
  }
}
?>

你應該傳遞一個連接對象(可能是PDO),並且各個地方應該能夠選擇它,作為參數,或者作為其他人引用的某個中心對象的屬性,或者其他東西。

擁有多個連接可能很有用,當你想要一個新連接時,mysql_connect選擇現有的連接似乎很瘋狂 - 但無論如何它都是瘋了。 只需使用PDO。

如果使用mysql_pconnect()函數,可以使用該方法,如果已經有mysql連接,將搜索它,如果找到它,它將不會創建另一個。

或者,如果你考慮也不在php中使用實例,你可以直接調用php數據庫對象,如:

class DB {}

DB::connect($host, $user, $pass);

如果使用此方法,則無需擔心多個連接。 當然,如果你需要一次使用多個連接到多個數據庫,你可以使用對象實例,或者創建你的類,這樣它就可以使用幾個參數並將它們全部存儲起來(不是很重新考慮這個)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM