Hi, after reading this question i wonder if someone can help me understand how to implement correctly Dependency Injection with these PHP Classes:
class DBClass
{
private $mMysqli;
function __construct(mysqli $database)
{
$this->mMysqli=$database;
}
function __destruct()
{
$this->mMysqli->close();
}
public function listUsers()
{
$query='SELECT * FROM Utente;';
$resultset=$this->mMysqli->query($query);
while($row = $resultset->fetch_array(MYSQLI_ASSOC)) {
echo $row['username'];
echo $row['pwd'];
echo "<br />\n";
}
}
public function runQuery($query)
{
return $resultset=$this->mMysqli->query($query);
}
public function getConnection()
{
return $this->mMysqli;
}
}
Session class:
class Session
{
private $_session;
public $maxTime;
private $database;
public function __construct(DBClass $database)
{
$this->database=$database;
$this->maxTime['access'] = time();
$this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');
session_set_save_handler(array($this,'_open'),
array($this,'_close'),
array($this,'_read'),
array($this,'_write'),
array($this,'_destroy'),
array($this,'_clean')
);
register_shutdown_function('session_write_close');
session_start();
...
}
}
User Class (for details about the currently logged in user):
class User
{
private $username;
private $role;
private $session;
function __construct($session)
{
$this->session=$session;
...
}
}
Externally:
$connection=new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
$database=new DBClass($connection);
$session=new Session($database);
$user=new User($session);
Is this the proper way?