Symfony Doctrine:检查与数据库的连接

问题描述 投票:0回答:2

有一段时间检查控制器中与数据库的连接工作正常,执行以下操作:

$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();

但我现在有一个弃用:

php.INFO:用户已弃用:已弃用对 Connection::connect() 的公共访问。

我现在应该如何测试我的数据库连接?

php symfony doctrine php-8 symfony6
2个回答
1
投票

现在在库外使用连接时有弃用通知:

Deprecation::triggerIfCalledFromOutside(
            'doctrine/dbal',
            'https://github.com/doctrine/dbal/issues/4966',
            'Public access to Connection::connect() is deprecated.',
        );

您需要使用

getNativeConnection()
(来自同一个 Connection 类

$em->getNativeConnection()->isConnected();

您可以阅读包含这些更改的 PR。


0
投票
Symfony 7.0.8 with Doctrine +2.11

#[Route('/api/check/database', methods:['POST'], name:'api_check_database')]
public function database(EntityManagerInterface $em): Response
{
    try {
        // ->connect() now is protected thus deprecated
        // ->isConnected() as no transaction response is null
        // Otherwise throws exception
        $connected = ! $em->getConnection()->isConnected();

        return $this->json([
            'status' => $em->getConnection()->isConnected(),
            'message' => $connected ? 'connected.' : 'failed.'
        ]);

    } catch (\Exception $e) {
        return $this->json([
            'status'  => false,
            'message' => 'Connect to database failed - Check connection params.',
            'error'   => $e->getMessage()
        ]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.