How do I share a MySQL connection over a class in PHP?

I want to share a MySQL connection with another class in PHP that contained a query. Therefore MySQL.php contains:

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

      

And the php file 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 this?

+3


source to share


2 answers


It's called dependency injection and is easy to implement. You are passing the parameter to your class directly when you create 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);

      

+3


source


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

Simple example:

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 always there.

0


source







All Articles