新手:如何在zend框架上正确设置数据库连接?
我对 OOP 和 Zend 还很陌生。到目前为止,我正在尝试建立数据库连接。我的 application.ini 文件中有这个:
resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname = "dbtest"
resources.db.isDefaultTableAdapter = true
据说我可以通过以下方式访问任何地方的数据库适配器:
$db = Zend_Db_Table::getDefaultAdapter();
问题是大多数指南假设您自动知道将其放置在哪里,但老实说我不知道。到目前为止我所做的是在我的 Index.php 模型中我有一个方法:
public function getPosts()
{
$db = Zend_Db_Table::getDefaultAdapter();
$sql = "SELECT * FROM posts";
$result = $db->fetchAll($sql);
return $result;
}
使用这个查询就可以了,但是如果我想创建更多方法来保存我的其他查询,每次我都必须调用 $db = Zend_Db_Table::getDefaultAdapter() 所以我确信我没有以有效的方式这样做。我已经尝试将其放入各种 __construct() 和 init() 方法中,但它不起作用。我应该在哪里添加代码而不必每次都调用它?谢谢。
I'm pretty new to OOP and Zend. So far I'm trying to set up a db connection. I have this in my application.ini file:
resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname = "dbtest"
resources.db.isDefaultTableAdapter = true
Supposedly I can access the db adapter everywhere with:
$db = Zend_Db_Table::getDefaultAdapter();
The problem is most guides assume you automatically know where to place that, but I honestly have no idea. What I'm doing so far is in my Index.php model I have a method:
public function getPosts()
{
$db = Zend_Db_Table::getDefaultAdapter();
$sql = "SELECT * FROM posts";
$result = $db->fetchAll($sql);
return $result;
}
With that one query it would be okay, but if I want to create more methods that hold my other queries each time I will have to call $db = Zend_Db_Table::getDefaultAdapter() so I'm sure I'm not doing this in an efficient way. I've already tried placing it in various __construct() and init() methods, but it wouldn't work. Where would I add the code without having to call it each time? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
运行查询的一种简单方法是为每个扩展
Zend_Db_Table_Abstract
的表创建一个类,这将为您提供一些方便的方法来帮助您从数据库中获取内容。使用此方法时,您将能够调用表格内容
以获取更具体的帖子,您也可以使用 id 通过 id 获取它
然后用于创建您可以使用的新条目
并用于更新
希望这对您有一点帮助,您可以找到更多信息请参见 ZF 官方文档 http://framework.zend.com /manual/fr/zend.db.table.html 和 http://framework.zend.com/manual/fr/zend.db.table.row.html
An easy way to run your queries would be to create a class for each of your tables that extends
Zend_Db_Table_Abstract
which would provide you some handy methods to help you get your stuff from your database.While using this method you will be able to call your table content through
for a more specific post you could also fetch it by id using
And then for creating new entries you could go with
And for updating
Hope this helps you a bit, you could find more info in the official ZF doc at http://framework.zend.com/manual/fr/zend.db.table.html and http://framework.zend.com/manual/fr/zend.db.table.row.html