将集合检索方法添加到模型中

问题描述:

Hey, I'm looking for a bit of advice here, I have a simple model with the usual save, delete and find methods, but wanted to create a getAll method aswell, it feels wrong putting it in the model as its not related to the actual model. Which way should I design this?

My current model looks like this:

<?php
class User {

    $id;
    $name;
    $address;

    public function __construct() {
        // do some constructor stuff    
    }

    public function save() {
        // insert into....  
    }

    public function delete() {
        // delete from user where ....
    }

    public function find($id) {
        // select * from user where ...     
    }
}
?>

Any help would be much appreciated, Thanks

嘿, 我在这里寻找一些建议,我有一个简单的模型与通常的保存, 删除和查找方法,但是想要创建一个getAll方法,将它放在模型中是错误的,因为它与实际模型无关。 我应该用哪种方式设计呢? p>

我当前的模型如下所示: p>

 &lt;?php 
class User {
 
 $ n id; 
 $  name; 
 $ address; 
 
 public function __construct(){
 //做一些构造函数
} 
 
 public function save(){
 //插入.... 
  } 
 
公共函数delete(){
 //从用户中删除.... 
} 
 
公共函数查找($ id){
 //从用户中选择* ...  
} 
} 
?&gt; 
  code>  pre> 
 
 

我们非常感谢任何帮助, 谢谢 p> div>

Well, after you have methods for finding, creating and deleting users, there's nothing to worry. In my opinion, there are two approaches

1) You can use your find() method in a special way, in order to get all users (a bit of a hack)
2) You can create a public static method getAll() to do the job (I think it should be static, because getAll() is not related to a single instance of User object)

Having the getAll() method inside the model is actually standard practice. There is nothing inherently detrimental about it.

For example in Zend Framework the Zend_Db_Table_Abstract base class has a built-in fetchAll() method. Codeigniter's internal ActiveRecord class implements get() which behaves similarly. Etc.

A model is a wider concept than CRUD and the number of methods is not restricted as long as they handle data.

It depends on what is "model" in your application.
If it's just representation of db table you can add findAll() or getAll() method to your model.
But if it's entity class it shouldn't know about the data source. You should add service and data mappers layers to your application.
If your application is quite small and additional layers will overload it - just use active record pattern.