从laravel core之外的文件中读取Laravel中的DB凭据

时间:2016-11-03 08:29:35

标签: php laravel

对不起,如果这个问题对某些人来说是微不足道的,但到目前为止我还没能做到并找到答案。在Laravel中,我们在app/config/database.php

中拥有数据库凭据
'connections' => array(
    ...

    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'myDB',
        'username'  => 'myUser',
        'password'  => 'myPass',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

    ...
),

现在我在public目录中有一个自定义文件,在libraries目录中有一个自定义文件,其中也包含数据库凭据

$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "myDB"; 

$conn = new mysqli($servername, $username, $password, $dbname);

有没有办法在某些方面将app/config/database.php包含在这些文件中并从中读取数据库凭据,而不是在3个文件中拥有数据库凭据?

2 个答案:

答案 0 :(得分:2)

如果test.php存在于您的公共文件夹中:

// test.php
$config = include __DIR__ . '/../app/config/database.php';
// var_dump($config);

$servername = $config['connections']['mysql']['host'];
$username   = $config['connections']['mysql']['username'];
$password   = $config['connections']['mysql']['password'];
$dbname     = $config['connections']['mysql']['database']; 

$conn = new mysqli($servername, $username, $password, $dbname);

答案 1 :(得分:1)

您可以include app/config/database.php文件,然后从那里读取凭据。

在自定义文件中,只需使用include 'path_to/app/config/database.php';,然后就可以从那里访问连接数组。为了帮助我们生成文件路径,我们可以使用__DIR__ magic constant;

include __DIR__ . '/../app/config/database.php';
$conn = new mysqli(connections['mysql']['host'], connections['mysql']['username'], connections['mysql']['password'], connections['mysql']['database']);