我是codeigniter的新手,但是我在做很多Rails开发时理解OOP和MVC.我还没想到的一件事是如何在codeigniter中编写类级方法并在控制器中访问它.例如,我有
<?php
class User_model extends Model {
function user_model()
{
parent::Model();
}
public static function get_total_users_count(){
$results = $this->db->query("SELECT * FROM bhr_users GROUP BY userid");
if($results){
return $results->num_rows();
}
return 0;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我认为我在这里所做的是为我的模型建立了一个类级别的方法,我应该能够User_model::get_total_users_count()在我的控制器中调用Now,之前的程序员称为"欢迎"我有类似的东西:
<?php
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
$this->load->model('bhr_model');
$this->load->model('user_model');
}
function index()
{
$invite = $this->uri->segment(3);
if($invite == 'invitefriends') {
$pagedata['invitefriends'] = $invite;
} else {
$pagedata['invitefriends'] = '';
}
$pagedata['numberofpeople'] = User_model::get_total_users_count();
$this->load->view('default_page', $pagedata);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的方法调用get_total_users_count不起作用,因为它说因为我在类级别函数中使用db方法get_total_users_count.换句话说,当我引用一个类时,$ this没有db方法.
所以现在我的问题更具理论性.我一直认为实例方法只应在方法作用于类的特定实例时使用.有道理,对吗?但是,get_total_users_count正在对所有"用户"采取行动并对其进行计数.它似乎应该是一个类级别的方法.你同意吗?如果这样做,你知道如何通过类级函数内的框架访问数据库吗?
谢谢!
由于您未实例化User_model,因此必须获取CI实例,然后将其用于数据库查询.
在get_total_users_count()里面:
$ci_ins =& get_instance();
$ci_ins->db->query();
Run Code Online (Sandbox Code Playgroud)