简体   繁体   中英

Which option is more efficient (database queries using PDO)

I'm building a class to deal with database operations and I decided to use PDO.

At first I decided to use static methods to simplify the calls, since the attributes don't change and the methods are independent, so I don't need to save the reference of the object. However, with this solution I would have to instanciate a new PDO object for every call of some method of such class, connect to the database, then prepare thge query and execute.

Bellow is an example of the base of a insert mnethod for this class:

public static function insert($table, $columns, $values){
    $dbConnection = new PDO('mysql:dbname='.self::$db.'; host='.self::$host.'; charset=utf8', self::$login, self::$pass);

    ... create the sql query and the associative array of values

    $stmt = $dbConnection->prepare($sql);
    $stmt->execute($array_aux);
}

So I'm wondering if instanciating the PDO object in every call is too inefficient and if it's best if I store the PDO reference and so, don't use static methods.

ps: I know that some people hate static methods, since they are hard to unit test, but in some cases they are pretty handy.

To give an example of @nikita2206's suggestion:

private $pdo = null;
private static function getDB(){
    if(is_null(self::$pdo)) self::$pdo = new PDO(...);
    return self::$pdo;
}
public static function insert($table, $columns, $values){
     $dbConnection  = self::getDB();
     ....
}

Mind you: your code, using static methods & variables like this becomes wholly untestable with mock-pdo objects... They're not that much better then global variables at this point, Dependancy Injection would be preferred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM