我认为没有“一种真正的方法”可以做到这一点(无论你读到什么)......如果它在你的模型中有意义,那么这对我来说听起来不错。当您说“其中许多字段需要标准化”时,我不确定您的意思是什么,以及为什么不能作为 UserEntity 的一部分来完成,但无论如何。也就是说,您很可能无需完全独立的对象类就可以完成您想要做的事情。
评论/批评:
您的建议并不真正符合严格的“对象”模型,即 UserData 只是由真正属于 UserEntity 属性的事物组成,并且与这些属性没有其他潜在关系。
我不太确定为什么您需要一个单独的对象在实体外部传递...如果您需要数据,为什么不能只传递 UserEntity 并从那里访问它?在将数据传递给 UserEntity 构造函数之前,您需要对数据执行什么操作,而这无法通过在 stdClass 的实例中收集数据然后在 UserEntity 中处理它来轻松完成?
如果是我,我会做类似以下的事情(例如,创建一个新用户):
<?
// assume an appropriately defined UserEntity class...
// I'm using stdClass just to keep the parameters together to pass all at once
// I'm assuming some basic user data passed from the browser
$user_data = (object) array(
'email' => $_REQUEST['email'],
'name' => $_REQUEST['name'],
'password' => $_REQUEST['password'],
'confirm_password' => $_REQUEST['confirm_password']
);
/*
validateData is static so it can be called before you create the new user
It takes the $user_data object to validate and, if necessary, modify fields.
It also takes a $create flag which indicates whether the data should be
checked to make sure all of the necessary fields are there to create the user
with. This allows you to call it on update with the $create flag unset and it
will pass validation even if it's missing otherwise required fields.
It returns $result, which indicates pass or failure, and the potentially modified
$user_data object
*/
$create = TRUE;
list($result, $user_data) = UserEntity::validateData($user_data, $create);
// equivalence allows you to pass back descriptive error messages
if ($result === TRUE) {
// create the user in the database, get back $user_id...
$user = new UserEntity($user_id, $user_data);
}
else {
// return error to user
}
// access user data either individually, or if you want just make a getter
// for the entire group of data, so you can use it just like you would a
// separate UserData object
send_double_opt_in($user->getUserData());
?>
编辑以解决提供的更多信息:
您说这些属性存在于 UserEntity 之外,并且它们可能独立存在...您的意思是这些属性可以被收集、使用和丢弃,甚至不打算用于 UserEntity 对象?如果是这种情况,那么单独的对象将完全适合该数据。如果不是,如果数据始终从属于现有或未来的 UserEntity,那么这些属性将永远不会“独立存在”......让我们称之为“全局数据”的观点。当您将整个系统视为一个整体,而不仅仅是时时刻刻的代码时,数据很可能“属于” UserEntity 类。
至于静态方法,我认为没有特别的理由避免它们(显然),但每个人都有自己的理由。许多其他架构会稍微复杂一些,但这里有一些选项:
- 验证构造函数中的数据。问题是,如果它不验证,您将不得不删除数据库条目。丑陋。
- 将数据库交互与数据验证一起移动到构造函数中。这可能会违反您首选的对象模型,您只需在对象创建后检查它的状态(即设置公共属性
$this->status = 'error'; 或类似的东西来告诉您发生了一些不好的事情,您将不得不句柄)。
- 创建一个独立的函数来验证数据。丑陋,因为这是一个专门与 UserEntity 和/或其数据相关的函数。
- 或者,只需按照您的建议创建一个单独的 UserData 对象并完成它。与第 2 步非常相似,您必须拥有某种
$status 属性来指示验证失败。