【发布时间】:2015-01-10 18:24:43
【问题描述】:
我正在从头开始重写一个项目,并想在此过程中尝试学习 MVC。在这种情况下,我选择了 Phalcon,并且仍在研究将教程转换为我自己的项目的基础知识。
我需要考虑两个“配置”设置。首先,我需要读取具有数据库凭据的配置文件(这可以正常工作)。
require_once('../fileconfig.php'); // Read config file
$init = new Phalcon\Config\Adapter\Php("../fileconfig.php"); //Convert it to array
但是一旦我有了它,我如何真正连接到数据库并将其添加到 $di-> (如果我理解正确,它实际上是全局类?最终,我想提取“select * from config" 到一个数组中,并将其用于应用程序配置。在这种情况下,var_dump($dbh) 返回“null”
//Connect to database
$di->set('db', function() use ($init) {
$dbh = new \Phalcon\Db\Adapter\Pdo\Mysql([
"host" => $init->database->host,
"username" => $init->database->username,
"password" => $init->database->password,
"dbname" => $init->database->dbname
]);
return $dbh;
});
var_dump($dbh); //returns null
如果我删除 $di-> 部分,该数组将返回我需要的数据,但它仍然无法帮助我弄清楚如何连接到数据库并使其对模型中的其他函数全局可用:
$dbh = new \Phalcon\Db\Adapter\Pdo\Mysql([
"host" => $init->database->host,
"username" => $init->database->username,
"password" => $init->database->password,
"dbname" => $init->database->dbname
]);
返回:
object(Phalcon\Db\Adapter\Pdo\Mysql)[28]
protected '_descriptor' =>
array (size=4)
'host' => string 'localhost' (length=9)
'username' => string 'testuser' (length=8)
'password' => string 'testpass' (length=8)
'dbname' => string 'testdb' (length=6)
This question 似乎接近我的要求,但更多的是关于错误处理而不是实际连接,我在那里没有看到我的问题的答案。
【问题讨论】: