PHP& Codeigniter - 如何将参数传递给模型? [英] PHP & Codeigniter - how to pass parameters to a model?

查看:346
本文介绍了PHP& Codeigniter - 如何将参数传递给模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码从我的控制器中初始化模型:

I am using the following code to initialize a model from within my controller:

$this->load->model('model_name');

是否可以修改上面的行,以便模型构造函数接收参数?我想在模型构造函数中使用下面的代码:

Is it possible to modify the above line somehow so that the model constructor recieves a parameter? I want to use the following code in the model constructor:

function __construct($param_var) {
   parent::Model();

   $this->$param_var = $param_var; //I'm not even sure this works in PHP..but different issue
}

这将是非常有益的,以便我可以重用我的模型类。谢谢。

This would be very helpful so that I can reuse my model classes. Thanks.

更新:
(从一个答案,我的原始问题解决... thanks!)
只是为了解释为什么我想要做到这一点:想法是能够重用一个模型类。所以基本上给一个简单的例子我想能够传递一个order_by变量到模型类,以便我可以重用在模型类中的逻辑(并动态地改变sql中的顺序值)创建一个单独的类或单独的函数。

UPDATE: (from one of the answers, my original question is solved..thanks!) Just to explain why I wanted to do this: the idea is to be able to reuse a model class. So basically to give a simple example I would like to be able to pass an "order_by" variable to the model class so that I can reuse the logic in the model class (and dynamically change the order-by value in the sql) without having to create a separate class or a separate function.

这是糟糕的设计吗?如果是这样,你可以解释为什么你不会做这样的事情,你怎么做呢?

Is this poor design? If so could you please explain why you wouldn't do something like this and how you would do it instead?

推荐答案

我看到你的推理,但我可以建议看对象关系映射。有一个用户为CodeIgniter制作的ORM库,名为 DataMapper ,我最近一直在使用。您可以使用控制器中的表作为对象,它可能更适合您的问题。

I see your reasoning for this, but may I suggest looking at Object-Relational Mapping for your database needs. There is a user-made ORM library for CodeIgniter called DataMapper that I've been using lately. You can use tables in your controllers as objects, and it may be a better fit for your problem.

这篇关于PHP& Codeigniter - 如何将参数传递给模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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