大佬教程收集整理的这篇文章主要介绍了php – 有人可以使用PDO给出基本“用户”对象系统的完美示例吗?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
/* 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; } } ?>@H_631_2@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); ?>
以上是大佬教程为你收集整理的php – 有人可以使用PDO给出基本“用户”对象系统的完美示例吗?全部内容,希望文章能够帮你解决php – 有人可以使用PDO给出基本“用户”对象系统的完美示例吗?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。