2

Let's assume I have this class at codeigniter:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller
{
    function header(){
        $this->load->model("options_model");
        $data['options'] = $this->options_model->get_options();
        $this->load->view("header", $data);
    }

    function content(){
        $this->load->view("content");
        // ...
    }

    function footer(){
        $this->load->model("options_model");
        $data['options'] = $this->options_model->get_options();
        $this->load->view("footer", $data);
    }

    function index(){
        $this->header();
        $this->content();
        $this->footer();
    }
}

As you see, I repeated calling options_model and the method get_options at both header and footer. Then, at index I called header and footer. How can I avoid repeating methods at this cases. Or what is the best way for cases like this?

2 Answers 2

2

You can call your model in application/config/autoload.php it will include in all your project as

$autoload['model'] = array('options_model'); 

If you want to upload under single controller. then you can call it inside construct

 public function __construct() 
    {
        parent::__construct();
        $this->load->model("options_model"); // load it here??
    }

Add correct spelling of functin it is function

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Saty. I know that I can use autoload.php But I wonders about calling get_options() in multiple functions. then I call them at one. if there is a way to avoid calling it in both header and footer to reduce the load at server and the number of executing the query at model.
0

To avoid calling model (get_options()) in both header I would prefer you to create custom helper for it and directly call it in view.

read more about it at https://www.codeigniter.com/user_guide/general/helpers.html

2 Comments

The link you've provided points to an old documentation. EllisLab is not in charge anymore and the new docs are at codeigniter.com
edthe major problem is not with calling the model itself, but with calling a the method get_optins() twice. I think that the query executed twice. and I would like to avoid that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.