在CodeIgniter中使用模型 [英] Using models in CodeIgniter

查看:42
本文介绍了在CodeIgniter中使用模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CI中使用模型的最佳做法是,有人可以向我解释吗?
维基百科中的一篇文章将CI模型称为完全可选的,很少需要是不是真的?

Can somebody explain to me when it's a good practice to use models in CI? An article in wikipedia was referring to CI models as "entirely optional and are rarely needed" is that true in any way?

推荐答案

说您需要调用一个名为 get_user_info 的函数,该函数从数据库中检索用户信息。您可能具有以下功能:

Say you needed to call a function called get_user_info that retrieves the users info from a database. You could have a function like this:

class Home extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        $user = $this->get_user_info($_SESSION['user_id']);
        echo "Hello " . $user['first_name'];
    }

    function get_user_info($user_id) {
        $query = $this->db->query("SELECT * FROM users WHERE user_id = ?", array($user_id));
        return $query->row_array();
    }
}

但是,如果您需要拨打 get_user_info 在另一页上?

However, what if you needed to call get_user_info on another page?

在这种情况下,您将不得不复制该函数并将其粘贴到每个页面中,从而难以维护如果您有很多页面(是否需要将查询更改为JOIN到另一个表上?)

In this scenario you would have to copy and paste the function into every page making it difficult to maintain if you have lots of pages (what if you needed to change the query to JOIN onto another table?)

这也与不要重复自己的原则

模型应处理所有数据逻辑和表示形式,返回的数据已经被加载到视图中。最常见的是,它们用作将数据库功能分组在一起的一种方式,使您无需更改所有控制器就可以更轻松地更改它们。

Models are meant to handle all data logic and representation, returning data already to be loaded into views. Most commonly they are used as a way of grouping database functions together making it easier for you to change them without modifying all of your controllers.

class User extends Model {

    function __construct() {
        parent::Model();
    }

    function get_user_info($user_id) {
        $query = $this->db->query("SELECT * FROM users WHERE user_id = ?", array($user_id));
        return $query->row_array();
    }

}

在上面,我们现在创建了一个名为 user 的模型。在我们的家庭控制器中,我们现在可以将代码更改为:

In the above we have now created a model called user. In our home controller we can now change the code to read:

class Home extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        $this->load->model('user');
        $user = $this->user->get_user_info($_SESSION['user_id']);
        echo "Hello " . $user['first_name'];
    }
}

现在您可以更改 get_user_info 函数,而不必更改依赖相同功能的X控制器的数量。

And now you can change your get_user_info function without having to change X number of controllers that rely on the same function.

这篇关于在CodeIgniter中使用模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆