Hope you can help me with this one: i have two classes: Database and Users. The Database connects to the database using PDO (inside the constructor) and has functions to alter tables, insert data, etc. The Users class will handle login, as well add/remove users. However, th开发者_如何学运维e Users class needs to connect to the database. How can i do this?
There are several things you could do:
Globals
$db = new Database();
class Users
{
public function foo()
{
global $db;
$db->query();
}
}
Setting a static variable
$db = new Database();
class Model
{
static public $db;
}
Model::$db = $db;
class Users extends Model
{
public function foo()
{
self::$db->query();
}
}
Use a singleton
class Database
{
private static $instance;
private function __construct()
{
}
public static function instance()
{
return self::$instance ? self::$instance : self::$instance = new self();
}
}
class Users
{
public function foo()
{
Database::instance()->query();
// or $db = Database::instance(); $db->query();
}
}
The one thing you want to avoid is creating a new database connection per model or class.
Same way you normally would, but it might help to make the database a class property:
<?php
class Users
{
protected $_db;
public function __construct(Database $database = null)
{
if (!$database) {
$database = new Database;
}
$this->_db = $database;
}
public function addUser($username)
{
// Do stuff ...
$this->_db->insert($data);
}
}
Then you can use the User class like:
<?php
$users = new Users;
$users->addUser('joebob');
Simply add a reference to the database class instance into Users:
class Users {
var $database;
function __construct() {
$this->database = new Database();
}
};
Alternatively, if Database is a singleton, just reference it directly.
One way to do so would be to create ONE shared instance of the database class, then use it as a global variable wherever needed.
Start by creating the instance anywhere in your project, just make sure it is in global space (not inside another class or function).
$DB = new Database();
Then to access the shared database object, just use the $GLOBALS built-in array:
class User {
function __construct() {
$DB = &$GLOBALS['DB'];
// do something
$DB->callSomeMethod();
}
...
}
As pointed out by @Ryan, namespace collisions are possible using this strategy. The best middle path out would be to convert the Database class into a singleton. Then it would store its own instance (translation: ONE connection no matter what) which could be accessed via a Database::getInstance() method.
This is my Users class:
class Users {
private $data;
private $db;
public function __construct() {
$db = Database::getInstance('localhost', 'database', 'root', '123456');
}
public function __get($key) {
return $this->data[$key];
}
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function test() {
foreach($this->db->query('table', '*', '', '', '', '', '0,5') as $value) {
$results .= $value['field1'] . "<br />";
}
return $results;
}
}
精彩评论