开发者

Is it okay for a model to populate its own properties?

开发者 https://www.devze.com 2023-04-08 19:41 出处:网络
If I have a model that essentially represents a single row in a d开发者_StackOverflow中文版atabase, is it scale-friendly and test-friendly, and all around okay practice to have it populate it\'s own p

If I have a model that essentially represents a single row in a d开发者_StackOverflow中文版atabase, 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)


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.


If you want to de-couple the data storage layer from the models itself, you should make it injectable.

If the models are the data storage abstraction, you don't need to care, you only need to inject the models which then should have defined interfaces so you have the rest of your application testable.

But it merely depends on your needs and your design.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号