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)
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:
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.