简体   繁体   中英

Codeigniter and Mongodb library - do I need a model?

I am trying my hand out with mongodb as a backend to my codeigniter application. I found and followed this example: http://www.surfinme.com/codeigniter-mongodb/

So I have the following structure:

+application\\ libraries\\ Mongo_db.php config\\ mongodb.php controllers\\ api.php

This is what my api.php file looks like so far:

<?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. But is that overkill?

Any comments would be appreciated.

Thanks.

Depends on how tightly you want to adhere to MVC principals.

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 . 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM