dongshandun4363 2013-08-01 10:29
浏览 26
已采纳

包含数据库查询的PHP构造函数构建对象,好/坏?

Is it bad practice to have a database query in the constructor for a class in order to load it upon creating a new instance of it?

class Home
{
    private $home_id = null;
    private $home_name = null;
    private $home_number = null;
    private $home_street = null;

    function __construct($home_id)
    {
        $do_query = $mysql_con->query("SELECT * FROM home WHERE home_id = '$home_id'");

        while ($home_data = $do_query->fetch_assoc())
        {
            // Set all of the items in the object
            $this->home_id = $home_data["home_id"];
            $this->home_name = $home_data["home_name"];
            $this->home_number = $home_data["home_number"];
            $this->home_street = $home_data["home_street"];
        }
    }
}

I have been told before that this might be bad practice, to have a query that builds up the object in the constructor.

  • If it is bad practice, why is it bad practice?
  • What is the alternative?
  • 写回答

3条回答 默认 最新

  • dougai0138 2013-08-01 10:53
    关注

    Your Home class is a domain object and those should ideally not be aware of how they're persisted.

    Separating the concerns allows for flexibility. This is also referred to as the Data Mapper pattern.

    class Home
    {
        public $home_id;
        public $home_name;
        public $home_number;
        public $home_street;
    }
    
    interface HomeMapperInterface
    {
        public function get($id);
    }
    
    class HomeMapper implements HomeMapperInterface
    {
        public function __construct($db)
        {
            $this->db = $db;
        }
    
        public function get($id)
        {
            $query = $this->db->query(...);
            if (($row = $do_query->fetch_assoc()) === false) {
                throw new RecordNotFoundException();
            }
    
            $home = new Home;
            $home->home_id = $row['home_id'];
            // ...
    
            return $home;
        }
    }
    

    To use it:

    $mapper = new HomeMapper($db);
    $home = $mapper->get(123);
    

    You can improve this by using Identifier Map to avoid loading the same record twice into separate objects.

    Btw, this is only a partial data mapper; it would also be used to update, insert and delete objects from your database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python