Welcome Guest, Not a member yet? Register   Sign In
Loading Model from View
#1

[eluser]Unknown[/eluser]
Hi,

This is the first project I am doing with codeigniter and I have become a bit stuck.

I am unsure if I am even attempting to go about this the right way so any help would be great.

When someone logs onto my site I am setting 2 session variables storing there user_id and a logged_on variable. When they visit a page I check to see if the logged_on variable is set, if it is not set then I show them a sign in page but if it is set I want to get there user data based on the user_id session variable. Todo this I am trying to access a model from the view.

View:
Code:
$user_id = $this->session->userdata('user_id');
$this->load->model(');
$this->user_model->user_id = $user_id;
$user_row = $this->user_model->get_user();

Model:
Code:
function get_user()
{
   $query = $this->db->query("SELECT * FROM users WHERE '$this->user_id' = user_id");
   return $query->result();
}

I get this message when trying to access the view:

Code:
Fatal error: Call to undefined method stdClass::get_user() in /var/www/system/application/views/_leftnav.php on line 21


Any help would be great Thanks.
#2

[eluser]Stefano G[/eluser]
Hello, basically you do one mistake... you shouldn't access a Model from a View because this violates the MVC pattern...

You should PASS all the data to the View from the Controller:

1) Login View
enter user/pass -> submit

2) Controller:
try login
login KO? -> show login view with error message
login OK? yes continue
read user data
...some other stuff...
load view passing data

PLEASE NOTICE:
try login means invoke a controller that checks against user table, so it would be a good idea to retrieve user data as well if user/pass are found...

Hope this is a bit clearer (even if I am in a hurry b/c I am at work Smile )

cheers

Stefano
#3

[eluser]Unknown[/eluser]
I had thought the same but then I had found this thread:

http://ellislab.com/forums/viewthread/64068/

My thinking is that it is best to do this code in the view as I am using the view as a header and as such it will be in all of the pages that I have.
#4

[eluser]Stefano G[/eluser]
I am sorry to disagree, but, if you code a SuperClass Controller, you could check if logged in before invoking a particular view, instead of coding that in the header...

maybe I am doing too much MVC philosophy, but usually the views are coded with the less logic possible (for maintenance issue).

Regarding authorization... what about using DX_Auth or ReduxAuthentication? they both include examples, docs and best practices.

regards

Stefano




Theme © iAndrew 2016 - Forum software by © MyBB