Reputation: 65
Today i've decided that I should start relying on a PHP framework because writing from scratch every time is really exhausting. As my framework I've chosen CodeIgniter, and I want to say It's amazing and easy to use. But I have some questions and confusion all over. I'm not pretty sure how to structre my website since I don't know when to use Models, and when to use Controllers.
What I have right now is:
// PAGES CONTROLLER
// As its name, this controller simply loads pages by a url query.
class Pages extends CI_Controller {
/*
* Constructor - loads the variables model.
*/
public function __construct() {
parent::__construct ();
$this->load->model ( 'variables' );
}
/*
* Displays a page by its name.
*/
public function view($page = 'home') {
if (! file_exists ( "application/views/pages/$page.php" )) {
show_404 ();
}
$data ['title'] = ucfirst ( $page );
$data ['variables'] = $this->variables;
$this->load->view ( "templates/header", $data );
$this->load->view ( "pages/$page", $data );
$this->load->view ( "templates/footer", $data );
}
}
// VARIABLES MODEL
// Used like a "mysql variables", all the data is taken from a table contains 2
// rows: id and value. and those variables are mostly used for site settings.
class Variables extends CI_Model {
/*
* Constructor, simply loads the database.
*/
public function __construct() {
$this->load->database ();
}
/*
* Gets a variable stored in the database.
*/
public function get($id) {
$query = $this->db->get_where ( 'variables', array (
'id' => $id
) );
return $query->row_array ()["value"];
}
/*
* Sets a variable stored in the database.
*/
public function set($id, $value) {
$this->db->where ( 'id', $id );
$this->db->update ( 'variables', array (
'value' => $value
) );
}
}
Am I using the correct hierarchy? Is there something I could change?
Now for my main question: lets say for example that I want to add a membership functionality for my websites. Should I do the following? :
Member Controller - Managing the current member, and all the forms actions are leading to this controller which communicates with the Members model(see below).
Members model - Handles all the database handling, functions like: login, register, getMember.
Upvotes: 0
Views: 163
Reputation: 1853
I just want to suggest in your controller you can do this in two lines:
$this->load->view ( "templates/header", $data );
$this->load->view ( "pages/$page", $data );
$this->load->view ( "templates/footer", $data );
Since you can load your view inside a view then you can try: In your view e.g template.php
$this->load->view('templates/header');
$this->load->view($main_content);
$this->load->view('templates/footer');
And you might want your controller on not having too much code because all heavy task should be in your model so in your controller :
$data['main_content'] = $page;
$this->load->view('templates/template',$data);
Upvotes: 2