Passing a function to a view in CodeIgniter?

Can I pass a function to a view in CodeIgniter? The function basically checks if the session value is set. For instance:

public function is_logged(){ $logged = $this->session->userdata('user_id'); if ($logged){ return true; } else { redirect('index'); } } 

Now I want to place this function on some of my views. so how can i pass this function to the view? Thanks.

+4
source share
2 answers

I would use a different approach, as @atno said: you are using the MVC pattern, so doing such checks in your view is logically incorrect, and also against the DRY approach.

I would do a controller check using the function that I have in the model and load the appropriate view according to the results:

 class Mycontroller extends CI_Controller { function index() //just an example { $this->load->model('mymodel'); if($this->mymodel->is_logged()) { $this->load->view('ok_page'); } else { $this->load->view('not_logged_view'); //OR redirect('another_page','refresh') } } } 

In your model:

  function is_logged() { $logged = $this->session->userdata('user_id'); if ($logged) { return TRUE; } else { return FALSE; } } 

If necessary, you need to do it programmatically, for each controller method (for example, to check the login), you can check inside the constructor:

  function __construct() { parent::__construct(); // check code here } 

Thus, you will have a check before calling any controller method, that is, when initializing the controllers.

UPDATE : using the model may be redundant here, you can just check what $ this-> session returns:

 function index() { // or mypage() or whatever if($this->session->user_data('user_id')) { $this->load->view('ok_page'); } else { $this->load->view('not_ok_page'); } } 
+1
source

You must not do this. Just use this code directly in your layout or just use it in your view.

You can also create an assistant: http://codeigniter.com/user_guide/general/helpers.html

0
source

All Articles