一个用户类,好方法?

时间:2011-01-07 13:35:45

标签: php design-patterns

我正在构建一个用户类来管理通用用户的创建,删除和修改。我的班级应该以这种方式使用:

# creation
user::create($username, $password, $email); // Does not need of $id

# modification
$u = new user($id);
$u->edit('password', $new_password);

# deletion
$u->delete();

基本上该类包含一个静态方法create(),它不需要使用id作为参数。创建后,您可以收集用户信息并管理用户创建类用户的实例,并将用户的$ id设置为参数。 这是一个很好的设计还是应该创建类似的东西:

# creation
$users = new genericUserMethod();
$users->create($username, $password, $email);

# modification
$u = new specificUser($id);
$u->edit('password', $new_password);

# deletion
$u->delete();

...创建2个不同的类。或者还有其他方法吗?

3 个答案:

答案 0 :(得分:3)

这可能是一种方法:

class User {
    private $id;
    private $name;
    //more fields here

    public function __construct($id = null) {
        $this->id = $id;
        if(!is_null($this->id)) {
            $this->load_user_data();
        }
    }

    protected function load_user_data() {
        //select from DB where id = $this->id and populate fields
    }

    public function save() {
        //if $this->id is null insert the user details in DB and populate $this->id with new user's id
        //else update DB with field (optionally check what has changed and update only if necessary)
    }

    public function delete() {
        //delete user if $this->id is not null
    }

    //fields getters and setters here as needed

}

使用示例:

$mary = new User(); //fresh new user
echo $mary->getId(); //returns null as this user is not inserted.
$mary->setName('mary');
$mary->save(); //insert user with name mary in the DB
echo $mary->getId(); // returns an id as this user is now inserted

$john = new User(2); // we assume there was a user john in DB with id = 2
echo $john->getName(); //echoes 'john' if this was his name in DB

您甚至可以在类中定义静态方法,例如getActiveUsers(),它返回一个包含活动用户的数组,例如......

注意:这是为了满足非常简单的需求,如果你需要做复杂的复杂事情,我建议你使用ORM库来指出@What是什么问题

答案 1 :(得分:3)

处理此问题的两种常用方法是Active RecordData mapperDoctrine 1使用Active记录模式,Doctrine 2使用Data Mapper。简而言之:
- 使用活动记录,您可以使用处理数据和持久性的类 - 使用Data Mapper,您拥有处理持久性的数据类和类

还有Data Access Object模式可以在上面提到的任何一个之上。

你的第一个例子看起来像活动记录模式,用于构建记录对象的不合理的静态简写(为什么没有多个构造函数或者可选的id - null表示new,null表示现有的)。

第二个示例在活动记录之上看起来像DAO,看起来更常见。

答案 2 :(得分:2)

第一个。也许你应该看看ActiveRecord / ActiveModel的一些进一步的灵感。