Php 用户类,好方法?
我正在构建一个用户类,用于管理泛型用户的创建、删除和修改。我的课堂应该这样使用:Php 用户类,好方法?,php,design-patterns,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(),该
# 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作为参数。创建之后,您可以收集用户信息并管理创建类user实例的用户,并将用户的$id设置为参数。
这是一个好的设计还是我应该创造一些类似的东西:
# creation
$users = new genericUserMethod();
$users->create($username, $password, $email);
# modification
$u = new specificUser($id);
$u->edit('password', $new_password);
# deletion
$u->delete();
…创建两个不同的类。或者还有别的办法吗?第一种。也许你应该看看ActiveRecord/ActiveModel以获得更多的启示。这可能是一种方法:
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 is the question两种常用的处理方法是和。1使用活动记录模式,原则2使用数据映射器。简而言之:
-有了活动记录,您就有了处理数据和持久性的类
-有了数据映射器,您就有了数据类和处理持久性的类 还有一种模式可以放在上面提到的任何一种之上 您的第一个示例看起来像是活动记录模式,用于构建记录对象的静态速记方式不合理(为什么不使用多个构造函数或可选的id-null表示新的,整数表示现有的)
第二个例子看起来像是活动记录上的DAO,看起来更普通。我也喜欢它,这就是我过去所做的。也许可以添加一些用法(创建新用户、加载旧用户、删除、编辑等)。。。除此之外,+1使用构造函数从数据库隐式加载对象不是“好的设计”。您不可能指示数据库中不存在给定的$id。此外,构造函数应仅用于创建类的新有效实例-1@mschneider您是对的,构造函数也可以设置为受保护的,并使2个静态方法“创建”和“加载”,例如,它在内部调用构造函数。。。但这只是一个简单的框架…@mschneider使用构造函数加载数据的方式是什么样的设计?我在大学里睡过头了什么?:)@Charlie:这叫做活动记录模式。查一查。