php 您可以从 CodeIgniter 中的另一个模型内部访问模型吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46338/
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
Can you access a model from inside another model in CodeIgniter?
提问by Eldila
I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter?
我正在使用需要身份验证的 CodeIgniter 编写一个 web 应用程序。我创建了一个模型来处理我的所有身份验证。但是,我找不到从另一个模型内部访问此身份验证模型的方法。有没有办法从另一种模式内部访问模型,或者有更好的方法来处理 CodeIgniter 内部的身份验证?
采纳答案by Till
In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model.
通常,您不想在对象内创建对象。这是一个坏习惯,相反,编写清晰的 API 并将模型注入您的模型。
<?php
// in your controller
$model1 = new Model1();
$model2 = new Model2();
$model2->setWhatever($model1);
?>
回答by Christian Davén
It seems you can load models inside models, although you probably should solve this another way. See CodeIgniter forumsfor a discussion.
似乎您可以在模型中加载模型,尽管您可能应该以另一种方式解决这个问题。请参阅CodeIgniter 论坛进行讨论。
class SomeModel extends Model
{
function doSomething($foo)
{
$CI =& get_instance();
$CI->load->model('SomeOtherModel','NiceName',true);
// use $CI instead of $this to query the other models
$CI->NiceName->doSomethingElse();
}
}
Also, I don't understand what Till is saying about that you shouldn't create objects inside objects. Of course you should! Sending objects as arguments looks much less clear to me.
另外,我不明白 Till 在说什么,你不应该在对象内部创建对象。你当然应该!将对象作为参数发送对我来说似乎不太清楚。
回答by Till
Don't handle authentication in your model. Only use models to interface with your database, or ldap or whatever.
不要在您的模型中处理身份验证。仅使用模型与您的数据库或 ldap 或其他任何东西进行交互。
I created an Auth library that I use to manage authentication and authorization. You can access a library like this from your controllers.
我创建了一个用于管理身份验证和授权的 Auth 库。您可以从控制器访问这样的库。
回答by saada
Loading a model within a model is now possible with the new CodeIgniter.
现在可以使用新的 CodeIgniter 在模型中加载模型。

