【发布时间】:2013-10-22 09:17:15
【问题描述】:
我希望看到一个系统的理想框架,该系统具有一组对象(即用户),其中数据包含在数据库中。有人建议我有一个 User 类和一个 UserMapper 类,这是我对它的外观的理解:
user.class.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;
}
}
?>
main.php
<?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);
?>
【问题讨论】:
-
好问题汤姆!您实际上是在尝试构建自己的 ORM。我建议查看这个问题:stackoverflow.com/questions/1664932/… 并在 Reddit 上就该主题进行一些很好的讨论:reddit.com/r/PHP/comments/164r3w/to_orm_or_not_to_orm
-
为什么不在
main.php的顶部声明一个,然后将它们用于脚本的其余部分?