php 在其他模型中访问 CodeIgniter 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/872623/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:11:03  来源:igfitidea点击:

Accessing CodeIgniter Models in Other Models

phpcodeigniter

提问by Click Upvote

It used to be that within a CodeIgniter model you couldn't access another model.

过去,在 CodeIgniter 模型中,您无法访问另一个模型。

$this->load->model('bar');
$this->bar->something();

Is this still valid, or have they changed it?

这仍然有效,还是他们改变了它?

回答by Phil Sturgeon

Those are some VERY long answers for a simple question.

对于一个简单的问题,这些是一些很长的答案。

Short answer:This is now fully supported. Cross-load away if you feel like it!

简短回答:现在完全支持。如果您愿意,可以交叉加载!

回答by oribani

I strongly disagree with the notion that a "model" should only encapsulate a database table with simple CRUD operations. As noted in the Wikipedia article:

我强烈不同意“模型”应该只用简单的 CRUD 操作封装数据库表的观点。正如维基百科文章中所述:

http://en.wikipedia.org/wiki/Model-view-controller#As_a_design_pattern

http://en.wikipedia.org/wiki/Model-view-controller#As_a_design_pattern

...that application layer is intended to do more than simply act as a single database table abstraction. Think about the meaning of the word "controller" -- it should act more as a director rather than being the entire application in and of itself. A "model" isa place for business logic. Most large scale applications in fact hold much of their business logic in the database itself (in the form of triggers, stored procedures, foreign keys, etc.).

...该应用程序层旨在做的不仅仅是作为单个数据库表抽象。想想“控制器”这个词的意思——它应该更像是一个控制器,而不是它本身的整个应用程序。“模型”业务逻辑的地方。大多数大型应用程序实际上在数据库本身中保存了大部分业务逻辑(以触发器、存储过程、外键等的形式)。

I think the misunderstanding of what a "model" is is partly caused by the same (over-)hype of "MVC", without carrying with it much understanding of the concepts themselves. Kinda like how empty "AJAX" is, or even more easy, "Web 2.0". For better or worse, plenty of script kiddies have jumped on the MVC wagon, and since the simple howtos and example scenarios don't do much more than tell you to put your database code in the "model", the misuse of that layer as only a database abstraction has become commonplace. Now you read posts all over the Internet calling it "unpure", "dirty", "hackish" to put any business logic in a model. That's WRONG. Misinformed.

我认为对“模型”是什么的误解部分是由“MVC”的相同(过度)炒作引起的,而没有对概念本身进行太多理解。有点像“AJAX”是多么空洞,或者更简单,“Web 2.0”。不管是好是坏,很多脚本小子都跳上了 MVC 的马车,而且由于简单的操作方法和示例场景并没有做更多的事情,只是告诉您将数据库代码放在“模型”中,因此滥用该层作为只有一个数据库抽象已经变得司空见惯。现在,您在 Internet 上阅读了称其为“不纯”、“肮脏”、“骇人听闻”的帖子,以将任何业务逻辑放入模型中。这是错误的。误导。

The easy example is to think about foreign keys: even if you only want your "model" to be a databasemodel, if you want to be "pure", "correct" or what have you, you really should be enforcing referential integrity therein. Thanks to the lack of real foreign key support in MySQL for many years, web applications grew up without anyone worrying about referential integrity at all. Fits the script kiddie lifestyle I guess. Anyhow, for even this simplified view of a model to be able to maintain foreign key validity, a model then has to work with others (or, especially if a framework like CodeIgniter does not let you do so, you have to write queries to other tables, sometimes duplicating queries elsewhere - THAT is bad style).

一个简单的例子是考虑外键:即使你只希望你的“模型”是一个数据库模型,如果你想要“纯粹”、“正确”或你有什么,你真的应该在其中强制执行参照完整性. 由于多年来 MySQL 缺乏真正的外键支持,Web 应用程序在成长过程中完全没有人担心引用完整性。我想适合脚本小子的生活方式。无论如何,即使模型的这种简化视图能够保持外键有效性,模型也必须与其他模型一起工作(或者,特别是如果像 CodeIgniter 这样的框架不允许您这样做,您必须将查询写入其他模型)表,有时会在其他地方复制查询 - 这是不好的风格)。

Therefore, I believe this to be a shortcoming of CodeIgniter. I understand that it might not be an easy fix, but it's certainly a disappointing oversight.

因此,我认为这是 CodeIgniter 的一个缺点。我知道这可能不是一个容易解决的问题,但这肯定是一个令人失望的疏忽。

So what I did was take the example code above and abstract it into a helper so that I now have a function that works almost identically to the normal $this->load->model() functionality. Here it is (put it into a helper that is auto-loaded and you can use it in any model):

所以我所做的是将上面的示例代码抽象为一个辅助函数,这样我现在就有了一个与正常的 $this->load->model() 功能几乎相同的函数。这是(将其放入自动加载的帮助程序中,您可以在任何模型中使用它):


   /**
    *
    * Allow models to use other models
    *
    * This is a substitute for the inability to load models
    * inside of other models in CodeIgniter.  Call it like
    * this:
    *
    * $salaries = model_load_model('salary');
    * ...
    * $salary = $salaries->get_salary($employee_id);
    *
    * @param string $model_name The name of the model that is to be loaded
    *
    * @return object The requested model object
    *
    */
   function model_load_model($model_name)
   {
      $CI =& get_instance();
      $CI->load->model($model_name);
      return $CI->$model_name;
   }

回答by MECU

It's possible, but not ideal and considered bad and more for "quick fix" than ideal or pure implementation.

这是可能的,但不是理想的,被认为是坏的,比理想或纯粹的实现更适合“快速修复”。

class Location extends Model{
      public function get($ID){
                // Get main CI object handle and load model
                $CI =& get_instance();
                $CI->load->model('LocationType');
                // Call new model functions using handle to main CI object
                $CI->LocationType->setID($result->LocationTypeID);
                $CI->LocationType->setTitle($result->TypeTitle);
                $this->_locationType = $CI->LocationType;
                //Other Stuff
    }
}

Anytime you're using the main CI object like this is probably a bad idea. Try to re-think your layout and just pass data to/from your controller to the models.

任何时候像这样使用主 CI 对象都可能是个坏主意。尝试重新考虑您的布局,只需将数据传入/传出控制器到模型。

http://codeigniter.com/forums/viewthread/69833/

http://codeigniter.com/forums/viewthread/69833/

回答by Dave Meybohm

You can load models from models as Phil Sturgeon says, but you have to be careful of dependencies if you load the models in the model constructor: if model A uses model B and model B uses model A, when you try to load one or the other, you'll go into an infinite loop.

您可以像 Phil Sturgeon 所说的那样从模型加载模型,但是如果您在模型构造函数中加载模型,则必须小心依赖关系:如果模型 A 使用模型 B 而模型 B 使用模型 A,那么当您尝试加载一个或否则,您将进入无限循环。

回答by Zbyszek

In situations like this in Code Igniter I prefer one of two posiibilities:

1) Have model's attribute and setter like this:

在 Code Igniter 中的这种情况下,我更喜欢以下两种可能性之一:

1) 具有这样的模型属性和 setter:

class X extends Model {
  var $Y_model;
  public function setY($Y) {
    $this->Y_model = $Y;
  }

  public function doItRightNow($a,$b) {
    $list = $this->Y_model->getSomeList($a,$b);
    // ...
  }
  // ...
}


And then use this setter before other methods to give an instance of other model so it can be used by methods.


然后在其他方法之前使用这个 setter 来给出其他模型的实例,以便方法可以使用它。

$this->load->model('X');
$this->load->model('Y');
$this->X->setY($this->Y);
$this->X->doItRightNow($something,$somethingElse);



2) To have a parameter in method by which I will give an other model instance from controller.



2)在方法中有一个参数,我将从控制器中提供另一个模型实例。

class X extends Model {
  public function doItRightNow($a,$b,$Y_model) {
    $list = $Y_model->getSomeList($a,$b);
    // ...
  }
  // ...
}

And use it like this:

并像这样使用它:

  $this->load->model('X');
  $this->load->model('Y');
  $this->X->doItRightNow($something,$somethingElse,$this->Y);



I think that these are more clean possibilities.
Which way to use depends on how many methods need to access other model. If there are one or two it might be better to give it as a method parameter. If more - I think it's better to have a class attribute and setter.
And in elegant way you can give one model or another depending on some condition - if they both partially implement same interface with the same kind of data returned (it's rarely useful, but it can be sometimes).



我认为这些是更干净的可能性。
使用哪种方式取决于访问其他模型需要多少方法。如果有一两个,最好将其作为方法参数提供。如果更多 - 我认为最好有一个类属性和设置器。
并且以优雅的方式,您可以根据某些条件给出一个或另一个模型 - 如果它们都部分实现相同的接口并返回相同类型的数据(这很少有用,但有时可能有用)。

回答by KyleFarris

I think it's generally better the write libraries that access the models and then include the libraries in your model if need be.

我认为通常最好编写访问模型的库,然后在需要时将库包含在您的模型中。

For instance, if you needed to check if someone is authorized to go through with a certain CRUD action, you might want to include whatever authentication library you are using (its probably auto-included in most cases). You wouldn't necessarily want to access the model directly--it just seems dirty and improper.

例如,如果您需要检查某人是否有权执行某个 CRUD 操作,您可能希望包含您正在使用的任何身份验证库(在大多数情况下它可能会自动包含)。您不一定想直接访问模型——它只是看起来很脏和不合适。

I think the preferred way is to do what you need to do in your controller and pass the results from one model's method(s), if need be, to your other model's method(s).

我认为首选的方法是在控制器中执行您需要执行的操作,并将一个模型方法的结果(如果需要)传递给另一个模型的方法。

Regardless, I can't see why it wouldn't be possible to include one model into another, per se. I don't think you can do it with the syntax you are showing, though. You would have to do it some other convoluted way. In any case, IMO, it's bad practice to include a model directly into another model.

无论如何,我不明白为什么不能将一个模型包含在另一个模型中。不过,我不认为你可以用你展示的语法来做到这一点。你必须用其他复杂的方式来做。无论如何,IMO,将模型直接包含到另一个模型中是不好的做法。

回答by phirschybar

In CI 2.0 you can just call one model directly from another.

在 CI 2.0 中,您可以直接从另一个模型调用一个模型。

回答by Lakin Mohapatra

Better to create a helper function instead of calling the function from another model so that it can be used in 2 models at a time and code can be reused.

最好创建一个辅助函数,而不是从另一个模型调用该函数,以便它可以一次在 2 个模型中使用,并且可以重用代码。