我希望看到一个系统的理想框架,该系统具有一组对象(即用户),其中数据包含在数据库中。有人建议我有一个 User 类和一个 UserMapper 类,这是我对它的外观的理解:
用户类.php
/* The class for constructing any user's information
*/
class User {
protected $userId, $email, $userGroup;
protected function getEmail() {
return $this->email;
}
protected function getUserId() {
return $this->userId;
}
public function __construct($userId, $email, $userGroup) {
$this->userId = $userId;
$this->email = $email;
$this->userGroup = $userGroup;
}
}
class UserMapper {
// database connection
private $db;
public function __construct($db)
{
$this->db = $db;
}
public function findByUserId ($userId) {
$userObject = new User();
$q = $this->db->prepare("SELECT userId, email, userGroup FROM user WHERE userId = :userId");
$q->bindValue(":userId", $id);
$q->setFetchMode( PDO::FETCH_INTO, $userObject);
$q->execute();
$q->fetch(PDO::FETCH_INTO);
return $userObject;
}
}
?>
主文件
<?php
include user.class.php;
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT => true));
$getUser = new UserMapper($dbh);
$user = $getUser->findByUserId(41);
echo $user->getEmail();
?>
但这在 main.php 方面似乎有点混乱。我可以不制作一个 PDO 对象并在我的所有脚本中定义它吗?以及 UserMapper 对象?或者每次我想从数据库中获取用户时,我是否需要创建一个新的 userMapper 对象,然后执行 findByUserId (如上)。或者有没有更简单的方法来做到这一点?
如果我想在 User 类中调用 UserGroup 对象,我该怎么做?(这也需要通过 PDO 连接到数据库)。执行以下操作似乎很混乱:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT => true));
$getUserGroup = new UserGroupMapper($dbh);
$userGroup = $getUserGroupMapper->findByUserId($this->userGroup);
?>