简体   繁体   中英

Don't we have to load the database class in the first place before we use any objects or methods in that class in codeigniter?

Here is some code excerpted from Codeigniter's user guide about models. There's no explicit load of the databass class, in which the object db , method get in the code below have to be defined. I've checked the autoload file, there is no autoload of this specific class.

class Blogmodel extends CI_Model {

    var $title   = '';
    var $content = '';
    var $date    = '';

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    function get_last_ten_entries()
    {
        $query = $this->db->get('entries', 10);
        return $query->result();
    }

    function insert_entry()
    {
        $this->title   = $_POST['title']; // please read the below note
        $this->content = $_POST['content'];
        $this->date    = time();

        $this->db->insert('entries', $this);
    }

    function update_entry()
    {
        $this->title   = $_POST['title'];
        $this->content = $_POST['content'];
        $this->date    = time();

        $this->db->update('entries', $this, array('id' => $_POST['id']));
    }

}

The CodeIgniter documentation states two methods of loading the database library and connection:

Database - User Guide

Automatically Connecting

The "auto connect" feature will load and instantiate the database class with every page load. To enable "auto connecting", add the word database to the library array, as indicated in the following file:

 application/config/autoload.php 

Manually Connecting

If only some of your pages require database connectivity you can manually connect to your database by adding this line of code in any function where it is needed, or in your class constructor to make the database available globally in that class.

$this->load->database();

Also, when loading the model as referenced by jss:

You can tell the model loading function to auto-connect by passing TRUE (boolean) via the third parameter, and connectivity settings, as defined in your database config file will be used:

$this->load->model('Model_name', '', TRUE);

If you scroll to the bottom of the Models page in the user guide where you got that example you'll see the section labeled Connecting to your Database , the first thing it explains is:

When a model is loaded it does NOT connect automatically to your database.

It then provides you with the three options for connecting that are available.

CodeIgniter automaticly load db class based on application/config/database.php

it does not need to in autoload section

more explonation is on http://codeigniter.com/user_guide/database/connecting.html

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