duanfeng3879 2011-09-26 22:24
浏览 11
已采纳

模型是否可以填充自己的属性?

If I have a model that essentially represents a single row in a database, is it scale-friendly and test-friendly, and all around okay practice to have it populate it's own properties, or should it have its properties injected, the same way you would inject an object?

Example:

Class blog {
    $id;
    $title;
    $body;

    public function load($id) {
        // db query to load id, title, body
    }
}

OR

Class blog {
    $id
    $title
    $body
}

// load blog data into $data, and then...

$blog = new Blog($data)
  • 写回答

2条回答 默认 最新

  • doufen3786 2011-09-26 22:31
    关注

    It's considered a bad practice to commingle database access inside your model classes directly. Injecting values is generally preferred.

    That said, if you were dead set on doing something like $model->load($id) and having it fetch from a datasource, you could get away with something like:

    class Model {
        private $_dataProvider;
    
        // inject data-provider dependency in constructor
        public function __construct($dataProvider){
            $this->_dataProvider = $dataProvider;
        } 
    
        public function loadById($id){
            $myData = $this->_dataProvider->loadDataById($id);
            $this->setFoo($myData['foo']);
            ...
        } 
    }
    

    By injecting a data access class, you can pass a mock in for testing, or replace your database with some web service, or whatever. As long as $dataProvider has a loadDataById() method that takes an int and returns the appropriate data structure, you're good.

    Personally, I prefer keep my models nice and focused on representing whatever it is they're modeling. I rely on external service classes and repositories to load data, inject it into models, and return them.

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

报告相同问题?

悬赏问题

  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误