CodeIgniter Model

3581 단어 CodeIgniterModel
1 The concept of model: The model is a PHP class specially used to deal with the database.
2 Analysis model: 1) Storage location: application/models/folder, you can also create subfolders in this folder
2) Basic model class example:
The filename of the class is application/models/user_model.php

<?php
<!-- lang: php -->
class User_model extends CI_Model{
<!-- lang: php -->
    function __construct(){
<!-- lang: php -->
        parent::__construct();
<!-- lang: php -->
    }
<!-- lang: php -->
}
<!-- lang: php -->
?>
3 Load the model in the controller
Syntax: his->load->model('Model_name);
Example: application/models/blog/queries.php

$this->load->model('blog/queries');
Once the model is loaded, it can be used in the following ways

$this->load->model('Model_name);
<!-- lang: php -->
$this->Model_name->function();
By default the model name is imported directly as the object name, as shown above, but it is also possible to have a more memorable object name such as:

$this->load->model('Model_name','fubar');
<!-- lang: php -->
$this->fubar->function();
4 Autoload Models: If you need a specific model that works across the entire project, you can have CodeIgniter autoload it on initialization
Method: Add this model to the autoload array in the applicaion/config/autoload.php file.
Note: The more memory is consumed when the model is loaded, the more memory is consumed. Automatic loading of models is at the expense of memory consumption. Try not to automatically load models that do not need to run through the entire site.
5 An example of a model:

class Blogmodel extends CI_Model{
<!-- lang: php -->
    var $title = '';
<!-- lang: php -->
    var $content = '';
<!-- lang: php -->
    var $date = '';
<!-- lang: php -->

<!-- lang: php -->
    function __construct(){
<!-- lang: php -->
        parent::__construct();
<!-- lang: php -->
    }
<!-- lang: php -->

<!-- lang: php -->
    function get_last_ten_entries(){
<!-- lang: php -->
        $query = $this->ldb->get('entires',10);
<!-- lang: php -->
        return $query->result();
<!-- lang: php -->
    }
<!-- lang: php -->

<!-- lang: php -->
    function insert_entry(){
<!-- lang: php -->
      $this->title = $_POST['title'];
<!-- lang: php -->
      $this->content = $_POST['content'];
<!-- lang: php -->
      $this->date = time();
<!-- lang: php -->

<!-- lang: php -->
       $this->db->insert('entries',$this);
<!-- lang: php -->
    }
<!-- lang: php -->

<!-- lang: php -->
    function update_entry(){
<!-- lang: php -->
        $this->title = $_POST['title'];
<!-- lang: php -->
        $this->content = $_POST['content'];
<!-- lang: php -->
        $this->date = time();
<!-- lang: php -->

<!-- lang: php -->
        $this->db->update('entries',$this,array('id' =>$_POST['id'])); 
<!-- lang: php -->
    }
<!-- lang: php -->
}
Note: Use $_POST directly, which is not very good, usually you should use the input class: $this->input->post('title');

좋은 웹페이지 즐겨찾기