我正在使用 codeigniter 开发网站。现在,通常当您在 codeigniter 中使用一个类时,您基本上就像使用静态类一样使用它。例如,如果我领导一个名为“用户”的模型,我会首先使用
加载它$this->load->model('user');
然后,我可以调用该用户类的方法,例如
$this->user->make_sandwitch('cheese');
在我正在构建的应用程序中,我想要一个 UserManagement 类,它使用一个名为“user”的类。
这样,例如我可以
$this->usermanager->by_id(3);
这将返回用户模型的实例,其中 id 为 3。 最好的方法是什么?
最佳答案
CI 中的模型类与其他语法中的模型类并不完全相同。在大多数情况下,模型实际上是某种形式的普通对象,带有与之交互的数据库层。另一方面,对于 CI,Model
表示返回通用对象的数据库层接口(interface)(它们在某些方面有点像数组)。我知道,我也觉得被骗了。
所以,如果你想让你的模型返回一些不是 stdClass
的东西,你需要包装数据库调用。
所以,这是我要做的:
创建一个包含您的模型类的 user_model_helper:
class User_model {
private $id;
public function __construct( stdClass $val )
{
$this->id = $val->id;
/* ... */
/*
The stdClass provided by CI will have one property per db column.
So, if you have the columns id, first_name, last_name the value the
db will return will have a first_name, last_name, and id properties.
Here is where you would do something with those.
*/
}
}
在 usermanager.php 中:
class Usermanager extends CI_Model {
public function __construct()
{
/* whatever you had before; */
$CI =& get_instance(); // use get_instance, it is less prone to failure
// in this context.
$CI->load->helper("user_model_helper");
}
public function by_id( $id )
{
$q = $this->db->from('users')->where('id', $id)->limit(1)->get();
return new User_model( $q->result() );
}
}
关于php - 模型类的 codeigniter 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6332552/