Passing the $ db object to other classes so that they can access the database

I have a PHP database class that connects to MySQL and completes all the PDO code, and I use it to query the database. Basically in the page controller, I create a new object:

$db = new Database($dbConfig);

Then I can get the data from the database using the prepared query:

$params = array('username' => $username);
$result = $db->preparedSelect('select password, salt from users where username = :username', $params);

Which copies the results of the PDO statement to the new destination array and only returns the database results back to the calling page. I go through them with a simple foreach as follows:

foreach ($result as $key => $val)
{
   $password = $val['password'];
   $salt = $val['salt'];
}

So let's say that I want another class to use my $ db object so that it can access the database in some methods. At the moment, another class is as follows:

class General
{
    // Database object
    private $db;

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

, , :

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

, . $db , , , , , .

- PHP5 $db & $db? PHP5 , , Java, , , . . ?

!

+5
3

, .

PHP5 "$ db", , "Foo *" C ++. , $db , , , . , , , . $db, , , , .

"& $db", "Foo **" C, , , , "Foo * &" ++. , , , , $db, $db , " " , .

- ( "&" ), , , .

+8

.

, $db, ===, , .

+3

That would be nice for static methods. Here's how many frameworks do the same thing.

class DB
{
   private static $db = FALSE:

   public static function init($dbConfig)
   {
      if(! self:$db)
      {
         self::$db = new Database($dbConfig);
      }
   }

   public static function preparedSelect($sql, $params)
   {
      if(! self::$db)
      {
         die("call the init method first");
      }

      // db stuff, where you would call $this->db call self::$db
   }
}

So, in your other classes, where you want to make calls to the database, all you have to do is:

class General
{
   public function __construct()
   {
      DB::init($dbConfig);
   }

   public function someMethod()
   {
      $params = array('username' => $username);
      $result = DB::preparedSelect('select password, salt from users where username = :username', $params);

   }
}
+3
source

All Articles