dongshenghe1833 2018-06-11 07:25
浏览 45
已采纳

PDO对象的最佳利用率

The system utilizes a single User class and most of the method utilize PDO to exchange the data with the database.

class User {

    private $db_server;
    private $db_login;
    private $db_pass;
    private $db;

    public function method_1(){
        $statement = new PDO("mysql:host=".$this->db_server.";dbname=".$this->db, $this->db_login, $this->db_pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
    //doing something with PDO
    }
// ...
    public function method_n(){
        $statement = new PDO("mysql:host=".$this->db_server.";dbname=".$this->db, $this->db_login, $this->db_pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
    //doing something with PDO
    }
}

The question is am I utilizing PDO effectively? Should I instantiate a PDO object as one of the class properties and pass it to every method that needs it, instead of instantiating a new PDO object in the method itself?

  • 写回答

1条回答 默认 最新

  • dongtao9887 2018-06-11 07:43
    关注

    you should take a look at Dependency Injection.

    The main idea is, that you inject the a composed and complete PDO-Object (the dependency) whilst creating User. Try to configure PDO only once in your application and get it through singleton-pattern. This way you have only this one instance.

    E.g.

    $pdo = new PDO($connString);
    $user = new User($pdo); 
    

    Be sure to add an object property to User, so you can access $this->pdo.

    This is only one approach how you could solve your problem, but it is not the most efficient way.

    If you are going to use the principle of the best practice way, you will not use a PDO-Object in User at all. Instead you would build an Object-Relational-Mapper (ORM). In this approach you would have a central Entity-Manager which holds the Database Adapter, in your case pdo. This entity-Manager would take User and can apply database operations on it, such as delete, create, update. You would define a general mapping, so that object properties equals table columns.

    Feel free to ask if you need more information :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大