the*_*ter 1 php mysql oop class
As of right now I have a database connection string included at the top of each of my pages. I'm then passing my database connection to the methods in my class like this:
public function select($db) {
//Code here
}
Run Code Online (Sandbox Code Playgroud)
Code on page:
$login_user->select($db);
Run Code Online (Sandbox Code Playgroud)
My thought is that if I ever want to query a different database I can just create a new connection string in my include file called $db2 and then I just pass that value instead of $db.
Is this a standard way of doing this or do you have a different recommendation?
将连接字符串传递给您的类有很多缺点并且没有任何好处。您的方向是正确的,但您希望传递数据库对象而不是连接字符串。
依赖注入是让类访问数据库的好方法,这只是意味着将依赖项(即数据库对象)传递给需要它们的对象,而不是对象本身从某种全局变量获取依赖项。
我建议您使用setDb()类上的方法来传递数据库对象,然后将其存储为属性以供任何内部使用。
例如,假设您已$db在初始化脚本中创建了数据库对象:
class SomeClass
{
protected $db;
public function setDb($db)
{
$this->db = $db;
}
public function something()
{
// do some query on the database using $this->db
}
}
$obj = new SomeClass();
$obj->setDb($db);
$obj->something();
Run Code Online (Sandbox Code Playgroud)
DI 为您带来了您提到的好处:能够轻松切换数据库,而无需在您的方法中做大量工作。还有其他好处,即易于测试。