samedi 17 octobre 2020

Passing Custom Namespaced PDO to Class Constructor? Fatal Error::__construct() must be an instance of PDO or null, instance of Services\DB_PDO given

Relatively new to OOP and design patterns. What would be the way to go about this this?

I created a PDO type handler service Class (idea was to create a class for PDO, have some limited queries, but create the class to make it reusable across the files in my project instead of having to initiate a PDO instance everytime) also in a folder services pdo.php

<?php
namespace Services;

protected static function configureInstance()
{
class DB_PDO {
    private $pdo = null;
    private $stmt = null;

    function __construct(){
        try {
            $this->pdo = new \PDO(
                DB_DSN,
                DB_USER, DB_PASS, [
                    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
                    \PDO::ATTR_EMULATE_PREPARES => false,
                ]
            );
        } catch (Exception $ex) { die($ex->getMessage()); }
    }

    function __destruct(){
        if ($this->stmt!==null) { $this->stmt = null; }
        if ($this->pdo!==null) { $this->pdo = null; }
    }
. . . . . . 
. . . . . . 

I have a class for my logging mechanisms called Log in a folder services log.php

<?php
namespace Services;

class Log {
protected static $instance;

.... eventually constructed with ...

    protected static function configureInstance()
    {
        $pdo = new \Services\DB_PDO();
        $log_handler = new \KarelWintersky\Monolog\KWPDOHandler($pdo, 'log');
        . . . 

Using monolog-pdo-handler library as the $log_handler

it's construct method is as followed:

public function __construct (\PDO $pdo, $table = 'log', $additional_fields = array(),
                             $additional_indexes = array(), $level = Logger::DEBUG,
                             $bubbling = true)

So you can already see why it is failing, as it is expecting an instance of a purely PDO object

Exact error is:

PHP Fatal error: Uncaught TypeError: Argument 1 passed to KarelWintersky\Monolog\KWPDOHandler::__construct() must be an instance of PDO, instance of Services\DB_PDO given, called in \app\services\log.php on line 111 and defined in vendor/karelwintersky/monolog-pdo-handler/src/KWPDOHandler.php on line 177

I realize I can fix this problem by just simply modifying KWPDOHandler.php and changing the __constructto (\Services\DB_PDO $pdo or something like that.

But that would be modifying the core library, and would cease to work with any updates.

Am I doing something fundamentally wrong here? What would be the appropriate way to go about this?

Aucun commentaire:

Enregistrer un commentaire