Alexey
Alexey

Reputation: 3637

Calling a Codeigniter controller function on view load

Task

Grab user's balance from Database on every new page load. Cannot store in session as there is a bonus system which can add to user's balance while he is logged in.

In the way my page is set up it has 4 parts:

$this->load->view('head'); //Head, meta, css, js
$this->load->view('navbar'); //Strip 50px height at top of page. Has navigation, logout and user balance
$this->load->view('xxx'); //Unique page content
$this->load->view('footer'); //standard footer

I can pass information to the view through the additional parameter:

$this->load->view('navbar', $balance);

However, that means everytime the page is called, I have to call the database from the controller somewhere.

What I am looking for is an idea of how to realize so everytime when I call the navbar view, it automatically calls a controller function which returns user balance.

I imagine something like this:

$this->load->view('navbar', function getBalance() {
   return callControllerAndGetBalance();
});

Had a dirty idea of putting an AJAX call in the navbar which on page load calls the controller and then changes the value, but that just seems wrong.

Any ideas?

Upvotes: 0

Views: 2023

Answers (1)

dmgig
dmgig

Reputation: 4568

You can use CodeIgniter hooks:

https://ellislab.com/codeigniter/user-guide/general/hooks.html

Untested, but this is how I think it must work. Taking this from that quora link I put in the comments, it looks like when you call $controller =& get_instance(); then that is the controller and you can add a property to it and it will be there for your view.

I'd play with the different options as well, this could be promising depending on what you are doing in your __construct method:

post_controller_constructor Called immediately after your controller is instantiated, but prior to any method calls happening.

class Blog extends CI_Controller{    

       public $balance = 0;

       public function getBalance(){        
             $this->balance = Balance::getMe();   
       }
}

What you can do is call the get_instance helper function from your hook.

class PostControllerHook{  
      function post_controller($params)  {     
          // $params[0] = 'controller' (given the params in the question)     
          // $controller is now your controller instance,     
          // the same instance that just handled the request     
          $controller =& get_instance();     
          $controller->getBalance();  
      }
}

then use

$this->load->view('navbar', $this->balance);

Upvotes: 2

Related Questions