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 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题