开发者

Adding collection retrieval methods into the model

Hey, I'm looking for a bit of advice here, I have a si开发者_高级运维mple 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


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)


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜