0

I want to use PDO for mysql connectivity in php. I need to have the PDO connection object which must be available on multiple files. The database connection must be also a class. Many answers found here are not satisfying. Please explain the correct method to achieve it.

The current method which I follow is: Filename:connectClass.php

<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
class connect
{
    public $db;
    public $isConnected;
    public function __construct()
    {
        $this->isConnected = true;
        try { 
            $this->db=new PDO('mysql:host=localhost;dbname=dbname','root','rootpass');
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        }
        catch(PDOException $e) { 
            $this->isConnected = false;
            throw new Exception($e->getMessage());
        }
    }
}
$obj=new connect();
?>

The connection object is accessed in Filename:addContentClass.php

<?php
include_once 'class/connectClass.php';
class addContent extends connect
{
    public function insertContent($title, $content, $page_title, $meta_tags) {
        try {
            $qry = $this->db->prepare("INSERT INTO tblPageContents (PageName, PageTitle, PageMeta, PageKeyWords, PageContents, PageFooter, PageShortName) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $data = array($title, $content, $page_title, $meta_tags);
            $qry->execute($data);  
            echo "<div id=\"dialog-ci\" title=\"Content updation success\" style=\"color:green\">Content insertion success</div>";
        }
        catch(PDOException $e)
        {
            echo 'Query failed'.$e->getMessage();
        }
    }
}
?>

The problem with this code is that I need to use extends every time.

Krishnadas PC
  • 5,981
  • 2
  • 53
  • 54
  • 2
    U always could use a singleton aproach. This way u can access the object from where ever, do note this is not the most suitable aproach. Depency injection is nicer... – DarkBee Sep 30 '14 at 11:27
  • @DarkBee Thanks for the fast response. Can you provide an example with two files. – Krishnadas PC Sep 30 '14 at 11:29
  • Give your connection variable (instance) in the constructor from the other class. – Daan Sep 30 '14 at 11:31
  • @KrishnadasPC you might find this approach useful: http://stackoverflow.com/a/11369679/727208 – tereško Oct 05 '14 at 07:18

1 Answers1

0

The singleton aproach can be achieved like this

<?php
class Connect {
    public $db;
    public $isConnected;
    public static $instance = null;

    public static function getInstance() {
        if (self::$instance == null) self::$instance = new static();
        return self::$instance;
    }

    private function __construct() {
        $this->isConnected = true;
        try { 
            $this->db = new PDO('mysql:host=localhost;dbname=dbname','root','rootpass');
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        }catch(PDOException $e) { 
            $this->isConnected = false;
            throw new Exception($e->getMessage());
        }
    }
}

class AddContent {
    public function insertContent($title, $content, $page_title, $meta_tags) {
        try {
            $qry = Connect::getInstance()->db->prepare("INSERT INTO tblPageContents (PageName, PageTitle, PageMeta, PageKeyWords, PageContents, PageFooter, PageShortName) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $data = array($title, $content, $page_title, $meta_tags);
            $qry->execute($data);  
            echo "<div id=\"dialog-ci\" title=\"Content updation success\" style=\"color:green\">Content insertion success</div>";
        }
        catch(PDOException $e)
        {
            echo 'Query failed'.$e->getMessage();
        }
    }
}

Do note this is not the best aproach because it's not a transmutable solution through other situations. Better would be to use depency injection and pass the instance of the connect class to your other classes

interface DatabaseImplementation {
    public function connect();
    public function execute();
    public function bar();
}

class Connect implements DatabaseImplementation {
    public function connect() {
        // Logic A...
        // ex. Connect to mysql with PDO
    }
    public function execute() {
        // logic A...
    }
    public function bar() {     
        return 'bar';
    }
}

class AlternativeConnect implements DatabaseImplementation {
    public function connect() {
        // Logic B...
        // ex. Connect to mongoDB
    }
    public function execute() {
        // logic B...
    }
    public function bar() {     
        return 'foo';
    }
}

class Controller {
    public function __construct() {
        $database_pdo = new Connect();
        $database_json = new AlternativeConnect();

        $pdo_content = new AddContent($database_pdo);
        $json_content = new AddContent($database_json);
    }
}

class AddContent {
    private $db;

    public function __construct(DatabaseImplementation $db) {
        $this->db = $db;
        $this->db->connect();
    }
}

The advantage of using DI is thatthe class does not need to know which implementation is used to store it data, whether it is with PDO or using MongoDB. It only needs to know which functions it can use (ex. connect / execute / ...)

DarkBee
  • 16,592
  • 6
  • 46
  • 58