是否可以在 Codeigniter 中动态扩展模型?
我在 CI 中的模型经过设置,以便在需要某些功能时加载“子”模型。为了使我的代码尽可能易于访问和干净,我希望这些子模型能够扩展它们被调用的模型。
因此,如果我有两个模型:
<?php
class Mymodel extends Model
{
}
并且:
<?php
class Submodel extends Model
{
function test() { do something.. }
}
然后我需要以某种方式让子模型扩展 mymodel,以便我可以执行类似 $this->mymodel->test()
>。子模型扩展的不一定是 mymodel,它可以是任何模型。有什么想法吗?
感谢您抽出时间。
my models in CI are set up so that they load "sub"-models whenever they need certain functions. In order to keep my code as accessible and clean as possible, I want those submodels to extend the model they are called to.
So if I have two models:
<?php
class Mymodel extends Model
{
}
And:
<?php
class Submodel extends Model
{
function test() { do something.. }
}
Then I need to, somehow, be able get the submodel to extend mymodel, so that I can do something like $this->mymodel->test()
. It doesn't have to be mymodel that submodel extends, it could be any model. Any ideas?
Thanks for your time.
您对类之间的继承的理解不正确。
继承只能以一种方式进行,即向下。
如果
Myodel extends Submodel
你的$this->mymodel->test()
可以工作,但它没有意义,因为子(子)对象应该继承来自父对象,而不是相反。打个比方,你不会看着一个孩子并告诉父母,“你看起来就像你的孩子”,因为孩子是父母的一部分代表。
您需要从字面上理解“扩展”这个词,您实际上是在“扩展”父级的功能。
===================
我相信您可以实现此目的的一种方法是创建幽灵函数,该函数只需加载正确的模型并调用该模型函数(尽管我不建议这样做) ,调试可能会变得非常混乱
因为根据您的示例
子模型
但是,如果您想要干净的代码,这不是正确的方法,请尝试观察继承,并在设计数据时牢记这一点。< /强>
You have an incorrect understanding of inheritance between classes.
Inheritance only flows one way, Down.
if
Myodel extends Submodel
your$this->mymodel->test()
would work, but it does not make sense as sub (child) objects are suppose to inherit from parent objects, not the other way around.As an analogy, you wouldn't look at a child and tell the parent, "You look just like your child", because it is the child that is a part representation of the parent.
you need to take the word
extends
very literally, you are literally 'extending' the functionality of the parent.===================
One way i believe you could accomplish this is to create ghost functions that simply load the proper model and call that models function (though I do not recommend this as it could get very confusing for debugging.
per your example
Submodel
BUT again, if you are going for clean code, this is NOT the way to go, try and observe inheritance, and design your data with that in mind.