I love coding
I love coding

Reputation: 1191

How to share MySQL connection over class in PHP?

I want to share a MySQL connection, with other class within PHP, which held the query to do. So MySQL.php contains:

    <?php
$user = 'username';
$passowrd = 'password';
$conn = new PDO('mysql:host=ip;dbname=DBName;port=3306',$user,$passowrd);
?>

And the php file, which I call MyLibrary.php contains:

    <?php
include 'DB.php';

class Manager {

    function jsonQuery() {

        $response = array ();


        $st = $conn->query ( "query");

        $response ["results"] = array ();

        foreach ( $st->fetchAll () as $row ) {

            //my stuff with the query
        }

        $response ["success"] = 1;

        echo json_encode ( $response );
    }

}

$object = new Manager();

$object->jsonQuery();

?>

So how can I do ?

Upvotes: 3

Views: 1915

Answers (2)

Frank
Frank

Reputation: 2043

I think the best way is to use a function, it is allways global :-)

Simple sample:

function &pdo() {
  $user = 'username';
  $passowrd = 'password';
  static $db = null;
  if($db===null)
    $db = new PDO('mysql:host=ip;dbname=DBName;port=3306',$user,$passowrd);
  return $db;
}

Alternative, but not good: use global:

function foo() {
  global $conn;
  # your code ....
}

or

$GLOBALS['conn'];

It is allways present.

Upvotes: 0

Machavity
Machavity

Reputation: 31614

It's called dependency injection and it's simple to implement. You pass the parameter into your class directly when you instantiate it. This way you never implement it more than once and you share that instance across your codebase

class Manager {
    /** @var \PDO */
    protected $pdo;

    public function __construct(\PDO $pdo) {
        $this->pdo = $pdo;
    }

    public function jsonQuery() {
        $response = array ();
        $st = $this->pdo->query("query");
        $response ["results"] = array();

        foreach ( $st->fetchAll() as $row ) {
            //my stuff with the query
        }

        $response ["success"] = 1;
        echo json_encode($response);
    }
}

$object = new Manager($conn);

Upvotes: 3

Related Questions