I’m working with a controller name page.php. This is what I have:
class Page extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
show_404();
}
public function view($id) {
$query = $this->db->query("
SELECT * FROM proposals
WHERE id='$id'");
if ($query->num_rows() == 1) {
$row = $query->row();
$data['proposal_id'] = $id;
$data['proposal_title'] = $row->title;
$data['proposal_proposer'] = $row->proposer;
$data['proposal_summary'] = $row->summary;
$data['proposal_description'] = $row->description;
$data['proposal_date'] = $row->date;
$data['proposal_vote'] = $row->vote;
$data['proposal_source'] = $row->source;
$query->free_result();
} else {
show_404();
}
// Get user data
$user_info['logged_in'] = "";
$user_info['username'] = "";
$user_info['user_id'] = "";
$user_info['score'] = "";
// Get special variables needed for the header
$header_data['page_title'] = htmlspecialchars($data['proposal_title']);
$header_data['page_description'] = htmlspecialchars($data['proposal_summary']);
// Get special variables needed for the footer
$footer_data['stats_proposals'] = "12";
$footer_data['stats_users'] = "42";
// Check if this is an edit
// Load the views (interfaces) in order
$this->load->view('templates/header', $header_data);
$this->load->view('page', $data);
$this->load->view('templates/footer', $footer_data);
}
}
As shown above, I am manually calling the header using $this->load->view('templates/header', $header_data); and passing some info to it. However, in my case, this info will always be the same across the site. There a way for me to call some sort of controller BEFORE loading the view for the header?
You could create a library & model to complete all your DB queries. This would also clean up the
$query = $this->db->query()bit so that it would be in your model rather than your controller.Then, each time you need to load the header view, you could use this in your controller:
The actual library would accept the variables needed to create this header view (for example,
$id). It would make a call to the model, which would perform any actual DB queries (for example,$query = $this->db->query("SELECT * FROM proposals WHERE id='$id'");). Then the library would make the data returned by the model usable by the view (for example, settingpage_title&page_descriptionto$row->title&$row->summary, respectively).