Wednesday, 15 January 2014

php - How should I structure my application in CodeIgniter? -



php - How should I structure my application in CodeIgniter? -

i'm designing php application code igniter framework , have structured in form of mvc i'm confused in sense of how should create things. current issue after user logs in session stored , accessed in controller model doesn't know current session find myself having pass userid every time want utilize model (ie update or user information) seems inefficient have maintain doing every time. i'm wondering if there improve way or if made error in way organized code.

example: have controller bunch of user methods. have logged in user in separate controller , using cookie , database session

create constructor in controller

public function __construct() { parent::__construct(); $this->load->model( 'users' ); // homecoming $user object if ( ! $this->user = $this->users->returnuserfromcookie() ) { redirect( '/login/', 'refresh' ); } // assign id else { $this->userid = $this->user->id ; } } //

if user object not come user model redirect login.

otherwise $this->userid available method in controller, method phone call in models, , of views call.

function showhistory(){ $history = $this->users->returnhistory($this->userid) ; }

and in case since have $this->user object can pull other info in method.

function sayhello(){ $data['greeting'] = 'hello ' . $this->user->first . ' ' . $this->user->last ; }

we didn't have pass $user or $this->user sayhello() because available. and don't have test if $this->user set because check done in constructor. if $this->user not set, controller never used.

you can assign $this->user $data. makes cleaner in views.

in controller method assign info , pass $data view

$data['user'] = $this->user ; $this->load->view( 'history', $data );

now in view don't need $this-> because have $user object.

<?php echo 'hello ' . $user->first . ' ' . $user->last ; ?>

========= edit

thank response, how access $user in model?

the exact same controller examples. $this->user->id , etc

like how model know user database operation on when phone call it.

its going user called (or returned) in constructor. if called $this->user id = 100 , available models.

php codeigniter

No comments:

Post a Comment