我不认为这是“一个正确的方法”来做到这一点(不管你了解它是什么)......如果它在你的模型是有道理的,那么它听起来不错。当你说“许多这些领域需要标准化”,以及为什么不能作为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 o bject?如果是这种情况,那么一个单独的对象将完全适合该数据。如果不是,如果数据总是从属于现有的或未来的用户实体,那么这些属性将永远不会“独立存在”,我们称之为“全局数据”。如果将整个系统视为一个整体,而不仅仅是代码,那么很可能数据“属于”UserEntity类。对于静态方法,我没有看到特别的理由来避免它们(显然),但是对于每一个他自己。许多其他体系结构会稍微复杂一些,但以下是一些选项:
- 验证构造函数中的数据。问题是,如果它不验证,你将不得不删除数据库条目。丑陋。
- 将数据库交互和数据验证一起移入构造函数。这可能会违反您首选的对象模型,您只需在创建对象后检查对象的状态(即设置一个公共属性
$this->status = 'error';
或类似的东西来告诉您发生了某些必须处理的不良事件) 。
- 创建一个独立的函数来验证数据。丑陋,因为这是一个与UserEntity和/或其数据特别相关的函数。
- 或者,只需创建一个单独的UserData对象,就像您建议的一样,并完成它。就像第二步一样,你必须有某种
$status
属性才能表明验证失败。
对我来说听起来不错:)据推测,你的ID字段是私人的,并且只有在你的UserEntity中获得()访问它...... – 2012-03-17 09:09:08
这将是想法:)但是任何可变属性的值设置器将在值对象。 – johnnietheblack 2012-03-17 17:17:50
简单地在实体对象上添加电子邮件,密码和所有其他字段有什么问题?有独立的数据对象给予什么好处? – 2012-03-20 13:05:27