PHP DataMapper pattern: My class needs an instance of PDO, I want to wrap it inside a Db class

萝らか妹 提交于 2019-12-04 14:51:03

You can use Factory pattern and create the PDO object within a function in the Database class.

class Database {
    private const connStr = 'mysql:host=.....';

    public static function createPDODatabase() {
        return new PDO(connStr);
    }
}

So you may call your EntryMapper constructor as:

$entryMapper = new EntryMapper(Database::createPDODatabase());

EDIT: If you want to do it by instantiating the Database object, you should call the PDO constructor in the constructor of the Database class.

class Database extends PDO {
    public function __construct($dbname='db_name', $server='localhost', $username='db_user', $password='db_password') {
        parent::__construct("mysql:host=$server;dbname=$dbname", $username, $password);
        parent::setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    }
}

Then you may just instantiate the Database object.

$entryMapper = new EntryMapper(new Database());
developer10

This is how I finally solved it (if a better implementation arises, I will for sure recode). It is an implementation of solution under the accepted answer here: Global or Singleton for database connection?

My ConnFactory.php

include('config/config.php');

class ConnFactory
{
    private static $factory;

    public static function getFactory()
    {
        if(!self::$factory){
            self::$factory = new ConnFactory();
            return self::$factory;
        }

    }

    private $db;

public function pdo()
{
    if(!$this->db){
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
        );
        $this->db = new PDO("mysql:host=".DB_HOST.";port=".DB_PORT.";dbname=".DB_SCHEMA."", DB_USER, DB_PASS, $options);
    }
    return $this->db;
    }

}

Usage in my view/html file (just a test of insert functionalty):

$entry = new Entry();
$entry->name = "Kartonaža ad Gradačac";
$entry->seoName = "kartonaza-ad-gradacac";
$entry->timeCreated = date("Y-m-d H:i:s");

$entryMapper = new EntryMapper(ConnFactory::getFactory()->pdo());
$entryMapper->saveEntry($entry);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!