php 在 CodeIgniter 中使用模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3228079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using models in CodeIgniter
提问by rabidmachine9
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?
有人可以向我解释什么时候在 CI 中使用模型是一个好习惯吗?维基百科中的一篇文章将 CI 模型称为“完全可选且很少需要”,这是真的吗?
回答by fire
Say you needed to call a function called get_user_infothat retrieves the users info from a database. You could have a function like this:
假设您需要调用一个get_user_info从数据库中检索用户信息的函数。你可以有这样的功能:
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();
}
}
However, what if you needed to call get_user_infoon another page?
但是,如果您需要get_user_info在另一个页面上调用怎么办?
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?)
在这种情况下,您必须将函数复制并粘贴到每个页面中,如果您有很多页面,则很难维护(如果您需要将查询更改为 JOIN 到另一个表上怎么办?)
This also goes against the don't repeat yourselfprinciple.
这也违背了不要重复自己的原则。
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();
}
}
In the above we have now created a model called user. In our home controller we can now change the code to read:
在上面,我们现在创建了一个名为user. 在我们的家庭控制器中,我们现在可以将代码更改为:
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'];
}
}
And now you can change your get_user_infofunction without having to change X number of controllers that rely on the same function.
现在您可以更改您的get_user_info功能,而无需更改依赖相同功能的 X 个控制器。
回答by musoNic80
No!! That's not true. Models are used as a layer between your controller and the database. MVC best practice is a subjective matter at best. People use it in different ways. A framework like CodeIgniter is great because it allows that level of flexibility. Other frameworks are much more strict. I'm general I try and keep my controllers very small and specific and put lots of code (db interaction and parsing results etc) in a model.
不!!这不是真的。模型用作控制器和数据库之间的层。MVC 最佳实践充其量只是一个主观问题。人们以不同的方式使用它。像 CodeIgniter 这样的框架很棒,因为它允许这种级别的灵活性。其他框架要严格得多。我一般会尽量让我的控制器非常小和具体,并在模型中放置大量代码(数据库交互和解析结果等)。
回答by DrColossos
Well a "model" reprensents data, most likely from a database (meaning your rows are returned from the database and the model holds the send data, simply said). There is no need to use the database layer given by CI - that is true- you can replace with another if you like, but that they are "rarely used" is simply not true.
好吧,“模型”代表数据,最有可能来自数据库(这意味着您的行是从数据库返回的,模型保存发送数据,简单地说)。没有必要使用 CI 提供的数据库层——这是真的——如果你愿意,你可以用另一个替换,但它们“很少使用”根本不是真的。
回答by Keyo
You should be using models to avoid replicating code (don't repeat yourself). I think most (nearly all) applications built with codeigniter would use models of some sort.
您应该使用模型来避免复制代码(不要重复自己)。我认为大多数(几乎所有)使用 codeigniter 构建的应用程序都会使用某种模型。
Perhaps the article is referring to the active record class, which is optional to use in models. Active record I find to be good for create, update and deletion but you'll most likely need sql for any slightly complex reads. It's worth noting that it's not just databases you can use in models. Web services or flat files or whatever source of data can be used in a model.
也许这篇文章指的是活动记录类,它在模型中是可选的。我发现活动记录适用于创建、更新和删除,但您很可能需要 sql 来进行任何稍微复杂的读取。值得注意的是,您不仅可以在模型中使用数据库。可以在模型中使用 Web 服务或平面文件或任何数据源。
I've been thinking of the models as a database layer only. They should not be, this creates bloating in your controllers. Using fat-controllers will slow you down in the end. Put your entire model structure in the model if you can and simply use the controller for logic.
我一直认为模型只是一个数据库层。它们不应该是,这会在您的控制器中造成膨胀。使用脂肪控制器最终会减慢你的速度。如果可以,将整个模型结构放在模型中,只需将控制器用于逻辑。
回答by Toni Leigh
There is a principle called 'fat model / skinny controller' which you might like to look at that suggests that the weight of your processing should be done in model files as oppose to controllers. This backs up the don't repeat yourself principle as outlined by @fire above as well as promoting re-use.
有一个称为“胖模型/瘦控制器”的原则,您可能想看看它表明您的处理权重应该在模型文件中完成,而不是控制器。这支持了上面@fire 概述的不要重复自己的原则以及促进重用。
I have found using this principle that I have ended up with a set of common, re-usable controllers that each use a set of re-usable models as well as, occasionally, project specific controllers used only once per site. As well as this I have cross dependency between models. I would not be able to re-use quite as frequently as I do without following the above principle and encapsulating as much processing as I can in the models.
我发现使用这个原则,我最终得到了一组通用的、可重用的控制器,每个控制器都使用一组可重用的模型,有时,每个站点只使用一次的项目特定控制器。除此之外,我在模型之间有交叉依赖。如果不遵循上述原则并在模型中尽可能多地封装处理,我将无法像我那样频繁地重复使用。
This subject gets a lot of discussion online so there is a lot of information to look at but it seems that on the Code Igniter boards it is recommended by the more experienced users.
这个主题在网上有很多讨论,所以有很多信息可以查看,但似乎在 Code Igniter 板上,更有经验的用户推荐它。
I have to add that 'entirely optional and are rarely needed' is generally not the case, I would say that this is plain wrong in anything but the most simple cases - the most simple cases being static pages which don't integrate with a database and just consist of a few loaded views, but even then using a model with a function in to retrieve a common set of views for each page would be advisable.
我必须补充一点,“完全可选且很少需要”通常不是这种情况,我会说这在任何情况下都是错误的,但最简单的情况 - 最简单的情况是不与数据库集成的静态页面并且只包含一些加载的视图,但即使这样,使用带有函数 in 的模型来检索每个页面的公共视图集也是可取的。
回答by cgwCode
This my Large model has lot of methods.
这个我的大模型有很多方法。
class Shortcode_model extends CI_Model {
public function __construct() {
parent::__construct();
$this -> load -> library('session');
}
/**
* Misc functions
*/
/**
* read keyword .
*
* @return void
* @author Chinthaka
**/
public function read($id) {
$this -> db -> select();
$this -> db -> from('short_code');
$this -> db -> where('id', $id);
$query = $this -> db -> get();
$result = $query -> row();
$shortcode = new stdClass();
$shortcode->id = $result->id;
$shortcode->code = $result->code;
$shortcode->aggregator = $result->aggregator;
$shortcode->mo_pp_id = $result->mo_pp_id;
$shortcode->mt_free_pp_id = $result->mt_free_pp_id;
$shortcode->mt_bill_pp_id = $result->mt_bill_pp_id;
$shortcode->partner_role_id = $result->partner_role_id;
$shortcode->partner_role_pass = $result->partner_role_pass;
$shortcode->product_id = $result->product_id;
$shortcode->billable = $result->billable;
// $shortcode->created = $result->created;
// $shortcode->changed = $result->changed;
$shortcode->status = $result->status;
//print_r($shortcode);
return $shortcode;
}
public function read_operator($telco_id){
$this -> db -> select();
$this -> db -> from('operator');
$this -> db -> where('telco_id', $telco_id);
$query = $this -> db -> get();
$result = $query -> row();
$operator = new stdClass();
$operator->id = $result->id;
$operator->code = $result->telco_id;
$operator->name = $result->telco_name;
return $operator;
}
/**
* create keyword .
*
* @return void
* @author Chinthaka
**/
public function create($arr_data) {
$this -> db -> insert('short_code', $arr_data);
//$stock['stock_id'] = $this->db->insert_id();
//return $query->result();
//return $keywords;
}
/**
* update keyword .
*
* @return void
* @author Chinthaka
**/
public function update($arr_data) {
$this -> db -> where('id', $arr_data['id']);
$this -> db -> update('short_code', $arr_data);
}
/**
* delete keyword .
*
* @return void
* @author Chinthaka
**/
public function delete($id) {
$this -> db -> where('id', $id);
$this -> db -> delete('short_code');
}
/**
* get all enabled shortcodes stored in the database.
*
* @return $shortcodess
* @author Chinthaka
**/
public function all_enable_shortcodes() {
$this -> db -> select();
$this -> db -> from('short_code');
$this -> db -> where('status', 'enable');
$this -> db -> order_by("code");
$query = $this -> db -> get();
$result = $query -> result_array();
//echo mysql_num_rows($result);
$shortcodes = array();
foreach ($result as $row) {
$shortcode = $this -> read($row['id']);
array_push($shortcodes, $shortcode);
}
/*while($data = $this->db->call_function('fetch_row', $result )) {
$shortcode = $this->read($data['id']);
array_push($shortcodes,$shortcode);
}*/
return $shortcodes;
}
/**
* check shortcode is exist.
*
* @return boolean
* @author Chinthaka
**/
function is_exists($shortcode, $id = 0) {
$this -> db -> where('code', $shortcode);
if ($id > 0) {
$this -> db -> where('id <>', $id);
}
$query = $this -> db -> get('short_code');
if ($query -> num_rows() > 0) {
return true;
} else {
return false;
}
}
public function get($short_code_id)
{
$query = $this->db->query('select * from short_code where id=?', array($short_code_id));
log_message('debug', $this->db->last_query());
return $query->row();
}
}
回答by rahijain
Models are for business logic(in ideal cases.. might be for debate, some people put buiness logic in controller) and DB connectivity in the MVC framework.
模型用于业务逻辑(在理想情况下......可能会引起争论,有些人将业务逻辑放在控制器中)和 MVC 框架中的数据库连接。
Read codeigniter user guide for more info on models.
阅读 codeignit 用户指南以获取有关模型的更多信息。

