drne47241 2011-08-13 13:55
浏览 53

如何在OOP中访问数据库类?

So I know that questions with 'what is the best' in their title aren't supposed to be asked, but really.. how should you do this?

We have a database class and, for example, a user class. A user class will get methods such as create() and update(), which will need to do database stuff.

As far as I know there are 2 main options, passing on the database object in every __construct() or make the database class static.

(Any other tips about OOP + database driven websites are also appreciated)

  • 写回答

5条回答 默认 最新

  • duanduo7400 2011-08-13 13:57
    关注

    A very common pattern here is to make the database class a singleton construct, which is then passed to every object constructor (that is called Dependency Injection).

    The purpose of making the database object a singleton is to ensure that only one connection is made per page load. If you need multiple connections for some reason, you would want to do it a different way. It's important to pass it via the constructors though, rather than creating the database object inside an unrelated class so that you can more easily test and debug your code.

    // Basic singleton pattern for DB class
    class DB
    {
    
      // Connection is a static property
      private static $connection;
    
      // Constructor is a private method so the class can't be directly instantiated with `new`
      private function __construct() {}
    
      // A private connect() method connects to your database and returns the connection object/resource
      private static function connect() {
        // use PDO, or MySQLi
        $conn = new mysqli(...);
        // Error checking, etc
        return $conn;
      }
    
      // Static method retrieves existing connection or creates a new one if it doesn't exist
      // via the connect() method
      public static function get_connection() {
        if (!self::$connection) {
          self::$connection = self::connect();
          // This could even call new mysqli() or new PDO() directly and skip the connect() method
          // self::$connection = new mysqli(...);
        }
        return self::$connection;
      }
    }
    
    class Other_Class
    {
    
      // accepts a DB in constructor
      public function __construct($database) {
        //stuff
      }
    }
    
    // Database is created by calling the static method get_connetion()
    $db = DB::get_connection();
    
    $otherclass = new Other_Class($db);
    
    // Later, to retrieve the connection again, if you don't use the variable $db
    // calling DB::get_connection() returns the same connection as before since it already exists
    $otherclass2 = new Other_Class(DB::get_connection());
    

    Another method is to create your database class directly extending either mysqli or PDO. In that case, the __construct() method supplies the object to getConnect(), as in

    public static function get_connection() {
      if (!self::$connection) {
        self::$connection = new self(/* params to constructor */);
      }
      return self::$connection;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统