我想要的是看到一个系统的理想框架,该系统具有一组对象(即用户),其中数据包含在数据库中.我被建议有一个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,$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',array(PDO::ATTR_PERSISTENT => true)); $getUserGroup = new UserGroupMapper($dbh); $userGroup = $getUserGroupMapper->findByUserId($this->userGroup); ?>
我能想到的一件事是让这个类成为一个单例,并在类的声明之上创建$user,所以每当你包含这个类时,你都会拥有该用户对象.
原文链接:https://www.f2er.com/php/136687.html