简体   繁体   中英

CodeIgniter load controller from view

Is there a way to load a controller from a view?

Here is what i am affter.. I want to use one view multiple times, but this view is being loaded by separate controller that gives the view, information from the db.So becouse of that information from the model i can't just set $this-load->view(); and etc. Is there a way to do this thing, or it has a better way?

I think a lot of sites face similar challenges, including one I'm working on that loads the same db content into the sidebar on almost every page in the site. I implemented this with the combination of a library and a helper:

  1. Put the data logic into the library (mine is named common.php). In addition to interfacing with the database, you may want the library to store the data in a local variable in case you want to reference it multiple times on a single load.
     public function get_total_items() { if ($this->_total_items === NULL) { $row = $this->ci->db->query("SELECT COUNT(*) FROM items")->row(); $this->_total_items = $row[0]; } return $this->_total_items; }
  2. Create a helper to load the library. (Don't load libraries within a view:) I have MY_text_helper that loads the library and returns the data:

     function total_items() { $CI =& get_instance(); return $CI->common->get_total_items(); }

  3. Call the helper function from within the view.

     <p> Total items: <?php echo total_items(); ?> </p>

Simply put, you can't and shouldn't load a controller from a view. That sad, I understand your frustration because you want to re-use the model-pulling/acting logic in the controller across multiples views.

There are various ways of doing this;

  1. Re-use the models. Your models should be very simple to select data from, and should be sleek, but if you're doing the same thing over and over it does seem stupid. In which case...

  2. Use a controller as a "main container" and extend upon it from any logic you need. So your basically using the controller as a template, which pulls data down from the model, loads the appropriate view.

MVC doesn't work that way... Just re-use the model - that's why it's separate from the controller. If that doesn't fit your needs, you should probably implement a library that does the logic.

just do this if you controller named controller1 put a link in view just like that

http://your-site.com/index.php/controller1/

if you want specific function add it to your url

http://your-site.com/index.php/controller1/myfunction

that's it

I would use a library .

That way you can wrap up the data retrieval in a reusable package that you can call from any controller you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM