[英]Codeigniter and Mongodb library - do I need a model?
I am trying my hand out with mongodb as a backend to my codeigniter application. 我正在尝试将mongodb用作我的codeigniter应用程序的后端。 I found and followed this example: http://www.surfinme.com/codeigniter-mongodb/
我找到并遵循以下示例: http : //www.surfinme.com/codeigniter-mongodb/
So I have the following structure: 所以我有以下结构:
+application\\ libraries\\ Mongo_db.php config\\ mongodb.php controllers\\ api.php +应用程序\\库\\ Mongo_db.php配置\\ mongodb.php控制器\\ api.php
This is what my api.php file looks like so far: 到目前为止,这是我的api.php文件的样子:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Api extends CI_Controller {
public function __construct()
{
parent::__construct();
//loading the mongodb library
$this->load->library('mongo_db');
}
public function index()
{
$data['main_content'] = "dashboard";
$this->load->view('includes/template',$data);
}
public function list_available()
{
//connect to mongodb collection (i.e., table) named as ‘surfinme_index’
$collection = $this->mongo_db->db->selectCollection('testcollection');
$result=$collection->find();
foreach($result as $data)
{
var_dump($data);
}
}
}
And the code seems to be working. 而且代码似乎可以正常工作。 It gets my data out of the database and dumps it to my browser.
它从数据库中获取我的数据,并将其转储到我的浏览器中。 But this "feels" wrong becuase I don't have a model.
但这“感觉”是错误的,因为我没有模型。 Or should I be viewing the library as my model layer?
还是应该将库作为模型层查看? I could just as easily create a file in the models folder called api_model and make the calls to the library from there.
我可以轻松地在models文件夹中创建一个名为api_model的文件,然后从那里进行对库的调用。 But is that overkill?
但这是过度杀伤力吗?
Any comments would be appreciated. 任何意见,将不胜感激。
Thanks. 谢谢。
Depends on how tightly you want to adhere to MVC principals. 取决于您要严格遵守MVC原则。
By creating a model for database operations you get several potential benefits. 通过为数据库操作创建模型,您可以获得一些潜在的好处。 First, it provides a source that can be reused by multiple controllers.
首先,它提供了可被多个控制器重用的源。 For example, there may be more than one controller that uses
selectCollection
. 例如,可能有多个使用
selectCollection
控制器。 Second, if for some reason you decide to change databases you only have to modify the Models as opposed to every controller that makes calls to mongo_db
. 其次,如果由于某种原因决定更改数据库,则只需修改模型,而不是对调用
mongo_db
每个控制器进行mongo_db
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.