Symfony: Doctrine - checking there's a connect

2019-07-31 10:42发布

问题:

Is there a simple way to debug why Doctrine is not connecting to MySQL?

config.yml has:

# Doctrine Configuration
doctrine:
    dbal:
        driver:   pdo_mysql
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"

and parameters.yml seems to have the correct connection information in it. E.g.

parameters:
    database_host: 127.0.0.1
    database_port: null
    database_name: <my database name>
    database_user: <my database user>
    database_password: <my database password>

However this piece of code still echoes out "Not connected".

    $cnx = $this->getDoctrine()->getConnection();
    if ($cnx->isConnected()){
        echo "Connected";
    }
    else {
        echo "Not connected";
    }

and I'm not getting any errors returned.

Any suggestions?

回答1:

This works:

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

$connected will be true to indicate it is connected.

The connect() establishes the connection, and then isConnected() returns a boolean to tell if it is connected.