clemens321 clemens321 - 6 months ago 30
PHP Question

Access PDO connection in fetchObject()-instance

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.

ml_ ml_
Answer

You can pass the PDO Instance so you don't have to call Application::getInstance()->getPDO() again.

public function save(PDO $dbh)
{
    $sth = $dbh->prepare('UPDATE main_user SET firstname = :firstname WHERE id = :id');
    $sth->execute([ 
        'id'        => $this->id,
        'firstname' => $this->firstname,
    ]);
} 
// and pass the (already available) $dbh to the save-Method at the buttom
$user->save($dbh);

or as CD001 mentioned in the comments, you can also pass it to the constructor:

class User
{
    // ...
    private $conn;

    public function __construct(PDO $conn)
    {
        $this->conn = $conn;
    }
}
// ... later at the bottom when fetching the Object:
$user = $sth->fetchObject('User', [ $dbh ]);
Comments