gpt4 book ai didi

php - PDO 使用类连接到数据库

转载 作者:行者123 更新时间:2023-11-29 23:17:20 25 4
gpt4 key购买 nike

我正在制作 PDO 系统并遇到问题。我要为我的代码、用户、产品等创建多个类。我想知道其中的联系。我的一个类上有这个:

class Database
{
private $_db;

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

$db 来自配置文件,我还在其中加载了所有类。现在的问题是:

我是否必须在所有类中创建相同的函数,或者我可以只拥有适用于我所有类的“数据库”类吗?

最佳答案

不,您不必 ( and shouldn't ) 为每个类一遍又一遍地创建相同的函数。这使得维护您的应用程序变得非常困难。

尝试以下方法之一:

1。依赖注入(inject)

您可以使用依赖注入(inject)来执行此操作。这是非常具体的情况,可能不是您正在寻找的内容,但我想无论如何我都会把它放在这里。

假设如下:

class Database
{
/**
* @var PDO
*/
private $db;

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

class User
{
/**
* @var Database
*/
private $db;

// Here we inject a Database object (as hinted by Database $db) into the current instance
public function __construct(Database $db)
{
$this->db = $db
}
}

try
{
$pdo = new PDO(...);
$db = new Database($pdo);
}

catch(PDOException $ex)
{
// Could not connect to database or some other error message
}



// Inject $db in the user class
$user = new User($db);

2。单例

您可以将数据库类设置为单例,然后静态调用它。这可能更符合您的需要。

class Database
{
/**
* @var Database
*/
private static $instance;

/**
* @var PDO
*/
private $db;

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

// You'd call this in your config
public static function initialize(PDO $db)
{
if(self::$instance == null)
{
// Create a new instance of this class
self::$instance = new self($db);
}
}

// Get the instance
public static function getInstance()
{
return self::$instance;
}

// Do something
public function doSomething()
{
// Do something
echo "Foo";
}
}

class User
{
public function doSomething()
{
// This would print "Foo"
Database::instance()->doSomething();
}
}

try
{
$db = new PDO(...);
}

catch(PDOException $ex)
{
// Could not connect to database or some other error message
}

Database::initialize($db);

$user = new User();

希望这有帮助。

关于php - PDO 使用类连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27660413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com