DB class having pdo, on inheriting should not re-initiate connection

Sailesh Jaiswal

When I'm calling different models in one then multiple times db connection establishes, I want only one, is it possible. Below is piece of my mvc

class Database{
    private $db;
    private $stmt;
    function __construct()
    {
        parent::__construct();
        $root = dirname(dirname(__FILE__));
        $this->config = parse_ini_file($root . '/app/config.ini', true);

        $db = $this->config['database settings'];
        $host = $db['host'];
        $user = $db['user'];
        $pword = $db['pword'];
        $db_name = $db['db'];
        $this->db = new PDO("mysql:host=$host;dbname=$db_name", $user, $pword, array(
            PDO::MYSQL_ATTR_FOUND_ROWS => true, PDO::ATTR_PERSISTENT => true
        ));
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);        
    }
    function executeQuery($query, $params = array())
    {
         $this->stmt = $this->db->prepare($query);
         if (! ($this->stmt)) {
           throw new Exception('Query failed while preparing');
         }
         try {
            $this->stmt->execute($params);
         } catch (PDOException $e) {
            throw $e;
         }
     }
     function getRecords($query, $params = array(), $array = false, $all = false)
     {
          $this->executeQuery($query, $params);

           $records = array();
          if ($this->totalRecords() > 0) {
             if ($array) {
                $this->stmt->setFetchMode(PDO::FETCH_ASSOC);
             } else {
                 $this->stmt->setFetchMode(PDO::FETCH_OBJ);
             }
            if ($all) {
               $records = $this->stmt->fetchAll();
            } else {
                while (($record = $this->stmt->fetch()) !== false) {
                   $records[] = $record;
               }
           }
        }
        return $records;
     }
  }

Below is the model where I use it

class TestModel extends Database{
  function __construct(){
    parent::__construct();
  }
  function getUsers(){
     return $this->getRecords("SELECT * FROM users");
  }
}

Below is another model I want to call the method getusers to use it for some purpose.

require("path_to_testmodel"); 
require("path_to_some_model");
require("path_to_some_other_model");
class TestModel2 extends Database{
    function __construct(){
       parent::__construct();
       $this->test_model = new TestModel();
       $this->some_model = new SomeModel();
       $this->some_other_model = new SomeOtherModel();
    }
    function doSomething(){
       $users = $this->test_model->getUsers();
    }
}

If I am including multiple models like TestModel() in one of the models, here seen is every time a database connection is established, sometimes I get too many connections error or in some system I get memory allocation issue.

Please help me to fix this.

pamelus

Try to save your DB connection in static property.

class Database{
    static private $theOnlyConnection = null;
    private $db;
    private $stmt;

    public function __construct()
    {
        parent::__construct(); // Database has no parent, what is this line for?
        if(null === self::$theOnlyConnection) {
            $root = dirname(dirname(__FILE__));
            $config = parse_ini_file($root . '/app/config.ini', true);

            $db = $config['database settings'];
            $host = $db['host'];
            $user = $db['user'];
            $pword = $db['pword'];
            $db_name = $db['db'];
            self::$theOnlyConnection = new PDO("mysql:host=$host;dbname=$db_name", $user, $pword, array(
                PDO::MYSQL_ATTR_FOUND_ROWS => true, PDO::ATTR_PERSISTENT => true
            ));
            self::$theOnlyConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            self::$theOnlyConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);        
        }

        $this->db = self::$theOnlyConnection;
    }

Note that this will cause connection to close at the end of your script, not on object destruction. It's OK for most use cases, yet if you want to disconnect from databse earlier, you'll need to track how many objects you have and destroy connection once the number is 0.

class Database{
    static private $theOnlyConnection = null;
    static private $modelObjectCount = 0;
    private $db;
    private $stmt;

    public function __construct()
    {
        self::$modelObjectCount++;
        if(null === self::$theOnlyConnection) {
            // connect
        }

        $this->db = self::$theOnlyConnection;
    }

    public function __destruct() {
        self::$modelObjectCount--;
        if(0 == self::$modelObjectCount) {
            // close connection
            self::$theOnlyConnection = null;
        }
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Class is not inheriting DB correctly

From Dev

datatables in pdo style - inject db connection into class causing errors

From Dev

PHP PDO Class connection

From Dev

PDO Connection and abstract class

From Dev

Database connection with PDO and Singleton class

From Dev

Is it ok to define PDO db connection in function?

From Dev

error handling if pdo db connection is not present?

From Dev

How to use the PDO connection work in the class

From Dev

making connection to database with PDO inside class

From Dev

PHP Out of class pdo connection fails

From Dev

Fetching Data from DB using PDO with Class

From Dev

How to initiate connection with JDBC on OpenShift?

From Dev

DB2 how to specify connection charset using PDO

From Dev

how to set the connection with a schema in a Postgresql DB with PDO PHP

From Dev

Should I pass Database connection or Cursor to a class

From Dev

Having PDO::fetch(PDO::FETCH_CLASS) return a null-valued instance of the object instead of a bool(false)

From Java

Why doesn't a class having private constructor prevent inheriting from this class? How to control which classes can inherit from a certain base?

From Dev

Is DB connection closed by the destructor of SqlConnection class?

From Dev

MySQL connection pooling in separate DB class - howto?

From Dev

inheriting and copying class variables

From Dev

Inheriting module/class methods

From Dev

Inheriting from a static class

From Dev

python - inheriting parent class

From Dev

Inheriting a patched class

From Dev

Inheriting class with primary constructor

From Dev

inheriting and copying class variables

From Dev

Inheriting from inner class

From Dev

Are there pros to inheriting a class template?

From Dev

Inheriting into Base Class Namespace

Related Related

  1. 1

    Class is not inheriting DB correctly

  2. 2

    datatables in pdo style - inject db connection into class causing errors

  3. 3

    PHP PDO Class connection

  4. 4

    PDO Connection and abstract class

  5. 5

    Database connection with PDO and Singleton class

  6. 6

    Is it ok to define PDO db connection in function?

  7. 7

    error handling if pdo db connection is not present?

  8. 8

    How to use the PDO connection work in the class

  9. 9

    making connection to database with PDO inside class

  10. 10

    PHP Out of class pdo connection fails

  11. 11

    Fetching Data from DB using PDO with Class

  12. 12

    How to initiate connection with JDBC on OpenShift?

  13. 13

    DB2 how to specify connection charset using PDO

  14. 14

    how to set the connection with a schema in a Postgresql DB with PDO PHP

  15. 15

    Should I pass Database connection or Cursor to a class

  16. 16

    Having PDO::fetch(PDO::FETCH_CLASS) return a null-valued instance of the object instead of a bool(false)

  17. 17

    Why doesn't a class having private constructor prevent inheriting from this class? How to control which classes can inherit from a certain base?

  18. 18

    Is DB connection closed by the destructor of SqlConnection class?

  19. 19

    MySQL connection pooling in separate DB class - howto?

  20. 20

    inheriting and copying class variables

  21. 21

    Inheriting module/class methods

  22. 22

    Inheriting from a static class

  23. 23

    python - inheriting parent class

  24. 24

    Inheriting a patched class

  25. 25

    Inheriting class with primary constructor

  26. 26

    inheriting and copying class variables

  27. 27

    Inheriting from inner class

  28. 28

    Are there pros to inheriting a class template?

  29. 29

    Inheriting into Base Class Namespace

HotTag

Archive