How can controllers and models communicate effectively in a PHP framework like Codeigniter?
Controllers and models can communicate effectively in a PHP framework like Codeigniter by using the built-in methods provided by the framework. Controllers can load models using the `$this->load->model('Model_name')` method and then call methods defined in the model to interact with the database. Models can return data to controllers using the `return` statement, allowing controllers to manipulate and pass data to views for displaying.
// Controller
class Example_controller extends CI_Controller {
public function index() {
$this->load->model('Example_model');
$data = $this->Example_model->get_data();
// Manipulate data
$processed_data = $this->process_data($data);
// Pass data to view
$this->load->view('example_view', ['data' => $processed_data]);
}
private function process_data($data) {
// Process data here
return $processed_data;
}
}
// Model
class Example_model extends CI_Model {
public function get_data() {
// Get data from database
$query = $this->db->get('example_table');
return $query->result();
}
}