在symfony中查找当前的Doctrine数据库连接设置

时间:2011-05-16 00:07:02

标签: symfony doctrine symfony1

我需要知道symfony项目中的数据库名称和数据库服务器名称。如何在symfony中使用编程方式访问当前数据库连接设置(使用Doctrine)?

5 个答案:

答案 0 :(得分:22)

假设您将EntityManager设为$this->em

从Symfony2获取Doctrine数据库名称:

$this->em->getConnection()->getDatabase();

从Symfony2获取Doctrine主机名(服务器名称):

$this->em->getConnection()->getHost();

您可以从连接中访问许多其他参数,例如usernameportpassword。有关详细信息,请参阅connection class

答案 1 :(得分:6)

例如:

foreach(Doctrine_Manager::getInstance()->getConnections() as $connection){
  $conn = $connection->getOptions();
  preg_match('/host=(.*);/', $conn['dsn'], $host);
  var_dump($host);
}

答案 2 :(得分:2)

特定conexion的dsn中的dbname:

databases.yml里

all:
  conexion1:
    class: sfDoctrineDatabase
    param:
      dsn: 'mysql:host=localhost;dbname=basegestion1'
      username: miusuario
      password: ********
  conexion2:
    class: sfDoctrineDatabase
    param:
      dsn: 'mysql:host=localhost;dbname=baseestadisticas1'
      username: miusuario
      password: ********

在行动中:

$mConexion1Options = Doctrine_Manager::getInstance()->getConnection('conexion1')->getOptions();
preg_match('/dbname=(.*)/', $mConexion1Options['dsn'], $mDbConexion1);

然后,dbname为:

echo $mDbConexion1[1]; //basegestion1

答案 3 :(得分:1)

使用此代码:

$myConnection           = Doctrine_Manager::getInstance()->getConnection('doctrine')->getOptions();
$dsnInfo                = $this->parseDsn($myConnection['dsn']);
$settings               = array();
$settings['dbUser']     = (string) $myConnection["username"];
$settings['dbPassword'] = (string) $myConnection["password"];
$settings['dbHost']     = (string) $dsnInfo["host"];
$settings['dbName']     = (string) $dsnInfo['dbname'];


private function parseDsn ($dsn)
{
  $dsnArray            = array();
  $dsnArray['phptype'] = substr($dsn, 0, strpos($dsn, ':'));
  preg_match('/dbname  = (\w+)/', $dsn, $dbname);
  $dsnArray['dbname']  = $dbname[1];
  preg_match('/host    = (\w+)/', $dsn, $host);
  $dsnArray['host']    = $host[1];

  return $dsnArray;
}

答案 4 :(得分:0)

试试这个

$conn = Doctrine_Manager::getInstance()->getConnection('doctrine')->getOptions();

$dns_array = split(';', $conn['dsn']);
preg_match('/host=(.*);/', $dns_array, $dbhost);
preg_match('/dbname=(.*)/', $dns_array, $dbname);

$dbname = $dbname;
$dbhost = $dbhost;
$dbuser = $conn['username'];
$dbpass = $conn['password']; 

<强>更新

作为Function split() is deprecated所以这是推荐的方式。

$dns_array = explode(';', $conn['dsn']);
preg_match('/host=(.*)/', $dns_array[0], $dbhost);
preg_match('/dbname=(.*)/', $dns_array[2], $dbname);

$dbhost = $dbhost[1];
$dbname = $dbname[1];
$dbuser = $conn['username'];
$dbpass = $conn['password'];