I'm refactoring parts of my application and replace some fetch(PDO::FETCH_ASSOC)
to dedicated classes with fetchObject()
.
Is there a way to access the pdo instance inside the generated class? See this example:
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();
Parts of my application use multiple databases and thus multiple pdo objects. To get reuseable code, I'd like to prevent using my global container class - and global
of course.