如何从Codeigniter中的控制器调用模型?

时间:2012-08-01 07:27:19

标签: php codeigniter

我想要一个网页,主要内容由ajax视图使用。和一个菜单边栏。

我的应用程序视图文件夹是

+pages
  -home
templates
  -header
  -footer

我的主页控制器是:

<?php 

class Pages extends CI_Controller {

        public function view($page = 'home')
        {
            $this->load->model('services_model');
            $data['records']= $this->services_model->getAll();
            if ( ! file_exists('application/views/pages/'.$page.'.php'))
            {
                // Whoops, we don't have a page for that!
                show_404();
            }

            $data['title'] = ucfirst($page); // Capitalize the first letter

            $this->load->view('templates/header', $data);
            $this->load->view('pages/'.$page, $data);
            $this->load->view('templates/footer', $data);

        }

}

我的service_model是:

<?php
class Services_model extends CI_Model {

    function getAll() {
        $q = $this->db->get('services');
        if($q->num_rows() > 0){
        foreach ($q->result() as $row)
        {
            $data[] = $row;

            }
        return $data;
    }
    }
}

我的观点是:

<ul class="blog-medium">
 <?php foreach($records as $row);?>
    <li>
    <div class="blog-medium-text">      
    <h1><a href="./post.html"><?php echo $row->title; ?></a></h1>
    <p class="blog-medium-excerpt">
    <?php echo $row->content; ?> <br />
    <a href="./post.html" class="read_more">Devamı &rarr;</a></p>
    </div>
    <div class="blog-medium-text"><p class="blog-info">
    <img src="./images/icon-time.png" alt="" />March 14, 2012 
    <img src="./images/sep.gif" alt="" /><img src="./images/icon-comment.png" alt="" />0 Yorum</p>
    </div></li>
    <?php endforeach;?>

所以我的问题是在代码中实现service_model。没有问题。你能告诉我一种正常工作的方法吗?

1 个答案:

答案 0 :(得分:1)

只需使用一个专用的控制器(ajax)进行所有ajax调用..

通用控制器

class Ajax_Controller extends CI_Controller {
  public function index(){
    // Add the logic which you want to share among all ajax calls
    // like doing security check and all
  }
}

扩展公共控制器以处理特定请求

class <SomeName>Ajax_Controller extends Ajax_Controller {
  public function <some_action>(){
    // write the request specific logic here.
  }
}