我想知道如何将我的连接存储在类变量中,然后继续重用它?现在我的代码看起来像这样
此功能现在设置我的连接,每次都调用
function setDB()
{
$serviceAccount = ServiceAccount::fromJsonFile('firebase_credentials.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
$db = $firebase->getDatabase();
return $db;
}
这是我需要连接$ db来获取和更新数据的函数之一。
function Period($gameid, $action)
{
$db = setDB();
$reference = $db->getReference('games/'.$gameid.'/Clock/CurrentPeriode');
$value = $reference->getValue();
if ($action =='m')
{
$value = $value -1;
$db->getReference('games/'.$gameid.'/Clock/CurrentPeriode')
->set($value);
} else {
$value = $value +1;
$db->getReference('games/'.$gameid.'/Clock/CurrentPeriode')
->set($value);
}
}
答案 0 :(得分:1)
解决方案是使用Singleton模式:
class DbConn
{
private $db;
protected function __construct()
{
$serviceAccount = ServiceAccount::fromJsonFile('firebase_credentials.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
$this->db = $firebase->getDatabase();
}
public function getInstance()
{
static $instance;
if (!$instance) {
$instance = new self();
}
return $instance;
}
public function getDb()
{
return $this->db;
}
}
使用情况将如下所示:
function Period($gameid, $action)
{
$db = DbConn::getInstance()->getDb();
$reference = .....
答案 1 :(得分:0)
您可以将setDB()转换为singletron类,从而存档您想要的内容。
答案 2 :(得分:0)
这里的每个人都在说使用单身模式。我会说不,不要将它作为答案:阅读here和here。
相反,我会使用不同的方法:依赖注入。使用该范例并在初始加载时实例化您的类,然后使用它从您的逻辑中抽象您的数据库层,使其更容易查询,而不是每次您想要查询或进行更改时都必须访问该部分。现在就做。
毕竟说完了,你的逻辑应该看起来像这样:
// in your top configuration that gets loaded with your framework
// probably in it's own config file
$Factory = new Factory();
$serviceAccount = ServiceAccount::fromJsonFile('firebase_credentials.json');
$DbContext = new DbContext($Factory, $serviceAccount);
// somewhere in your app
$GamesRepository = new GamesRepository($DbContext);
// your logic in some function or part of the app
$gameId = 1;
$value = $GamesRepository->getCurrentPeriode($gameId);
$action == 'm' ? $value++ : $value--;
$GamesRepository->setCurrentPeriode($value, $gameId);
因为您的存储库正在使用从初始加载页面处理数据库连接的另一个类来处理所有数据库连接,所以您可以继续使用某种模型或存储库来获取所需的信息。我可以对此进行扩展,但我认为你应该只考虑一下你的架构,如果你认为单例模式不是最好的用例,或者想要尝试不同的方法,你应该用你已经知道的东西来捅它。 39; s的缺点。