How to call model from controller in Codeigniter?

2019-07-07 07:05发布

问题:

I want a webpage , which main content is used by ajax view. and a menu sidebar.

my application views folder is

+pages
  -home
templates
  -header
  -footer

My main pages controller is :

<?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);

        }

}

My service_model is:

<?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;
    }
    }
}

And my view is :

<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;?>

so my problem is in implementing service_model in the code., there is no problem . Can you show me a way to work correctly?

回答1:

Just use one dedicated controller(ajax) for all your ajax calls..

A common controller

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
  }
}

extend the common controller to handle specific request

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