我在重构我的应用程序的某些部分,并将fetch(PDO::FETCH_ASSOC)
替换为fetchObject()
的专用类。访问fetchObject()中的PDO连接 - 实例
有没有办法在生成的类中访问pdo实例?看到这个例子:
class User
{
private $id;
private $username;
private $firstname;
private $lastname;
public function setFirstname($newValue)
{
if (empty($newValue) || !is_string($newValue)) throw new Exception('Wrong');
$this->firstname = $newValue;
}
public function save()
{
// IMPORTANT PART:
// I don't want to use the global object container here
$dbh = Application::getInstance()->getPDO();
$sth = $dbh->prepare('UPDATE main_user SET firstname = :firstname WHERE id = :id');
$sth->execute([
'id' => $this->id,
'firstname' => $this->firstname,
]);
}
}
$dbh = $application->getPDO();
$sth = $dbh->prepare('SELECT * FROM main_user WHERE id = ?');
$sth->execute([ 10 ]);
$user = $sth->fetchObject('User');
$user->setFirstname('Test');
$user->save();
我的应用程序的部分使用多个数据库,因此多个pdo对象。为了获得可重用的代码,我想阻止使用我的全局容器类 - 当然还有global
。
创建一个类成员(例如'User :: $ conn')并将PDO连接作为参数传递给构造函数以进行设置? – CD001