1

I want to be able to call a function which connects to my database, without creating multiple objects, including or having to write the same construct in each class. I Basically want to call a construct function in other classes. like this below.

class Database{

  public function __construct(){
    $this->conn = new mysqli("host", "user", "password", "db");

    //  Check   connection
    if  (!$this->conn)  {
      die("Connection   failed: ".mysqli_connect_error());
    }
  }
}

class User{
// call Database->__construct();

}

class OtherClass{
// call Database->__construct();
}

ofcourse this isn't the way to go but i don't really know what would be a viable way.

I thought maybe this would work. but it doesn't Making a new Database object in class to construct a connection

class Database{

  public function __construct(){
    $this->conn = new mysqli("host", "user", "password", "db");

    //  Check   connection
    if  (!$this->conn) {
      die("Connection   failed: ".mysqli_connect_error());
    }
  }
}

class User{
  $conn = new Database();
}

Dependecy injection or constructor injection seems like a nice solution. But i don't know if it's made for something like this and how to apply it.

class Database{

  public function connection(){
    $this->conn = new mysqli("host", "user", "password", "db");

    //  Check   connection
    if  (!$this->conn) {
      die("Connection   failed: ".mysqli_connect_error());
    }
  }
}

class User{

  private $db;
  public function __construct(Database $conn){
    $this->db = $conn;
  }

}
3
  • create singleton class to establish connection and then use the class anywhere. define as static so you dont need to instantiate. i can post an example of singleton class to establish db connection if you need though Commented Mar 28, 2017 at 18:40
  • @webDev would really appreciate that, I don't really know what you mean with singleton class. And how you would call it. Commented Mar 28, 2017 at 18:45
  • Have a look at this example: sourcemaking.com/design_patterns/singleton/php/1 You have to take your time to understand it. A simple alternative is to initialize, at the start of your PHP script, a globally scoped variable $database with your database connection in it, and simply use that everywhere. Why not? Works very well. Commented Mar 28, 2017 at 20:06

1 Answer 1

2

Here what i am doing for connection

class DBConnection{
    protected static $db;
    private function __construct() {
        try {
            self::$db = new PDO( 'mysql:host=localhost;dbname=db_abc', 'root', '' );
            //self::$db = new PDO( 'mysql:host=localhost;dbname=db_phonebook', 'root', 'QAZwsx2016!' );
            self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        }
        catch (PDOException $e) {
            echo "Connection Error: " . $e->getMessage();
        }
    }
    public static function getInstance() {
        if (!self::$db) {
            new DBConnection();
        }
        return self::$db;
    }

    public function __destruct() {
        $db=NULL;
    }
}

And here how I am using to another model class

class User{
    private $db;
    public function __construct() {
        $this->db = DBConnection::getInstance();
    }
    public function getUsers(){
        //....................
        //....................
        //$sql = 
        $query = $this->db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $query->execute();
        $customers = $query->fetchAll();
        //return .........

    }

If you want pure OOP way, please look into the factory methods, and look facade design pattern, Its all about how you gonna achieve some this.

This one is my way (simple way) but to architecture better see the different design patterns. One useful article here link and
Design Patterns with PHP-The right way link

Sign up to request clarification or add additional context in comments.

2 Comments

By making the $db static, its would only work with one database connection at a time, right?
you can have multiple database connection by defining multiple singleton classes for connection and include in your model class. example shows only one connection class. update that class and create another class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.