Is there a significant difference in using an object oriented approach over a procedural approach when implementing mysql in php? On the php website about mysqli_query
, (http://www.php.net/manual/en/mysqli.query.php), it provides an example of both, and I just want to know if there is any significant performance difference, or just know when to use each of them.
The answer to which one is better is "it depends." As with anything, there are a variety of different approaches and you should also keep in mind that code that uses objects is not necessarily object oriented but can still be written procedurally. In the same vein, code that does not use objects can still be modular.
I would choose to use the mysqli
class every time, though. There is no significant difference in performance. You probably won't realize some of the advantages of using a DB class such as simplified polymorphism, so my only argument for using the class is that I prefer the syntax. However, rather than use mysqli
directly I would probably recommend that you extend or compose it. You can only do this with the class.
class DB extends mysqli {
public function __construct() {
parent::__construct($_SERVER['DB_HOST'],
$_SERVER['DB_USER'], $_SERVER['DB_PASS']);
}
}
This is a very shallow example.
An example of the polymorphism I was talking about above would be something like this:
class User implements DAO {
private $db;
public function __construct(DB $db) {
$this->db = $db;
}
}
//Testing code is simplified compared to using it in production
class TestDB extends DB {}
new User(new TestDB);
new User(new DB);
By the way I categorically prefer PDO
over mysqli