Zend Framwork 2 - mysqli 连接配置和测试示例 [英] Zend Framwork 2 - mysqli connection configuration and testing example
问题描述
我正在尝试通过给定的框架应用程序学习 Zend Framework 2,但是我以前没有任何 Zend 经验.我确实从其他框架了解 MVC,例如yii,symfony.
I am trying learn Zend Framework 2 via the skeleton application given, however I don't have any kind of previous experience in Zend. I do know about MVC from other frameworks e.g. yii, symfony.
我的骨架应用程序似乎加载良好,然后下一步是将 MySQL db 连接配置到应用程序中.所以我尝试了以下问题的答案:
My skeleton app seems to be loading fine, then the next step is to configure a MySQL db connection into the application. So I tried following question's answer:
但这对我不起作用,所以我想知道为什么.我的代码是:
But that didnt work for me, so I am wondering why. My code is:
在 config/autoload/
文件夹中,我创建了一个名为 db.local.php
的文件并添加了以下内容:
In the config/autoload/
folder I created a file called db.local.php
and added the following:
return array(
'db' => array(
'driver' => 'Mysqli',
'database' => 'xxx',
'username' => 'sxxx',
'password' => 'xxxE',
'hostname' => 'localhost'
),
'service_manager' => array(
'aliases' => array(
'db' => 'Zend\Db\Adapter\Adapter',
),
),
);
在文件 IndexController.php 中 /module/Application/src/Application/Controller
的默认控制器中,我添加了以下内容来测试数据库,但我没有看到任何错误或此控制器的任何输出:
And in the default controller in /module/Application/src/Application/Controller
in file IndexController.php i have added the following to test the db, but I don't see any errors or any output from this controller:
public function indexAction()
{
$this->layout()->myvar = 'bla';
$db=$this->getServiceLocator()->get('db');
//var_dump($db); nothing comes here too.
$statement= $db->query('SELECT * FROM `ew_content` WHERE `con_id` = 1');
var_dump($statement); // this also empty
$isconnected = $db->getDriver()->getConnection()->isConnected();
if($isconnected){
$message = 'connected';
} else {
$message = 'not Valid data field';
}
//no output here either
return new ViewModel(array(
'customMessageForgotPassword' => 'Error!',
));
}
推荐答案
感谢 akond,实际问题似乎是我在服务管理器配置中对 db 对象进行了工厂创建.所以我必须将以下行添加到 db.local.php
thanks for akond, the actual issue looks like i have do a factory creation of the db object in the service manager config. So i have to add the following line to the db.local.php
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
配置的完整工作代码如下,
full working code for the configuration is below,
return array(
'db' => array(
'driver' => 'Mysqli',
'username' => 'xxx',
'password' => 'xxx',
'database' => 'xxxx',
'host' => 'localhost'
),
'service_manager' => array(
'factories' => array(
'translator' => 'MvcTranslator',
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
'aliases' => array(
'db' => 'Zend\Db\Adapter\Adapter',
),
),
);
这篇关于Zend Framwork 2 - mysqli 连接配置和测试示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!