问题描述
示例:
class UserStorage {
public function addUser(User $user) { //saves to db }
}
class User {
public function setName($name);
}
如果我将用户添加到用户存储中,然后又更改该用户对象该怎么办?在这种情况下,您可能会争辩说,仅应将用户对象存储在__destruct上.但这有时不是一个选择(例如,假设用户随后被显示和更新).
What if I add a user to the user storage and later change that user object? In this case you might argue that user objects only should be stored on __destruct. But sometimes this isn't an option (eg imagine the user is displayed and updated afterwards).
推荐答案
隐式写入数据库可能不是一个好主意.那应该是一个明确的,受控的操作.
Implicit writes to the database are probably a bad idea. That should be an explicit, controlled operation.
您的模式对我来说有点奇怪,但是我认为这是您想要的方式
Your pattern is a little weird to me, but I think this how you'd want to do it
class UserStorage
{
const ACTION_INSERT = 'INSERT';
const ACTION_UPDATE = 'UDPATE';
public function addUser(User $user)
{
$this->saveUser($user, self::ACTION_INSERT);
}
public function updateUser(User $user)
{
$this->saveUser($user, self::ACTION_UPDATE);
}
protected function saveUser(User $user, $action)
{
switch ($action) {
case self::ACTION_INSERT:
// INSERT query
break;
case self::ACTION_UPDATE:
// UPDATE query
break;
default:
throw new Exception('Unsupported action');
}
}
}
class User
{
public function setName($name)
{
// whatever
}
}
$userStorage = new UserStorage();
$user = new User();
$userStorage->addUser($user);
$user->setName('Peter');
try {
$userStorage->updateUser($user);
} catch (Exception $e) {
echo "There was an error saving this user: " . $e->getMessage();
}
但就我个人而言,我并不为此类设计感到疯狂.有一些为此而建立的模式,这些模式不太容易混淆,例如 ActiveRecord .
But Personally I'm not crazy about this class design. There are some well-established patterns for this that are less confusing, such as ActiveRecord.
这篇关于存储或使用对象状态后更改对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!