模型可以填充自己的属性吗?
如果我有一个本质上代表数据库中的单行的模型,那么它是否适合扩展且适合测试,并且可以让其填充自己的属性,或者应该注入其属性,就像您一样会注入一个对象吗?
示例:
Class blog {
$id;
$title;
$body;
public function load($id) {
// db query to load id, title, body
}
}
或
Class blog {
$id
$title
$body
}
// load blog data into $data, and then...
$blog = new Blog($data)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
直接在模型类中混合数据库访问被认为是一种不好的做法。通常首选注入值。
也就是说,如果您执意要做 $model->load($id) 之类的事情并让它从数据源中获取,那么您可以这样做:
通过注入数据访问类,您可以传递模拟进行测试,或者用某些 Web 服务替换数据库,或者其他什么。只要 $dataProvider 有一个接受 int 并返回适当数据结构的 loadDataById() 方法,就可以了。
就我个人而言,我更喜欢让我的模型保持良好状态,并专注于代表他们正在建模的任何内容。我依靠外部服务类和存储库来加载数据、将其注入模型并返回它们。
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.
如果您想将数据存储层与模型本身解耦,则应该使其可注入。
如果模型是数据存储抽象,那么您不需要关心,您只需要注入模型,然后模型应该具有定义的接口,以便您可以测试应用程序的其余部分。
但这仅取决于您的需求和设计。
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.