Differences in procedural and object-oriented implementations of mysql in php? [closed]

旧城冷巷雨未停 提交于 2019-12-07 18:18:30

问题


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.


回答1:


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




回答2:


As you are an intern it would be advisable to find out who is going to maintain the code in the future.

  1. Nobody in company.Go with OOP ,if you are happy with this, as OOP is the current practice.
  2. In House. Go with current practice,hopefully OOP



回答3:


Nope, there is no difference.

But you're overlooking way more important thing: no raw mysqi API functions have to be used in the application code, neither OOP or procedural.

There is one thing unknown to PHP users: API calls aren't intended to be used as is. They have to be wrapped in some sort of library. Without it mysqli is just a pain in the back, it require 2 times more code than old good mysql ext.

So, it does matter if you are using such a layer, but it doesn't matter if it is written using procedural or OOP inside.

Yet this library ought to be built in the form of class. There is just no other way.



来源:https://stackoverflow.com/questions/17252201/differences-in-procedural-and-object-oriented-implementations-of-mysql-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!