0

I have a block of code I'd like to put in my CI 2.x core folder and reuse via a base controller that would be extended by all of my other controllers.

Here is the code that appears in every controller and I want to move to somewhere more central:

$data['navigation'] = generate_navigation();  // helper function
$data['country'] = code2country();  // helper function
$data['langs'] = $this->select_country_model->get_langs();

// Get copy and images for page
$query = $this->common_model->get_content('markets', 'architectural');

// Load title, description and keywords tags with data
foreach ($query as $row) {
    $data['title'] = $row->page_title;
    $data['description'] = $row->description;
    $data['keywords'] = $row->keywords;
}

How do I put this in my base controller (MY_controller.php) and then send the data to my view from the extended controller. Do I still use $data[] = and $this->load->view('whatever', $data)?

1 Answer 1

1

Yeah, you can still pass this along in a $data variable, but you'll need to assign it so that you can access it from the other controller like this:

class MY_Controller extends CI_Controller {

    var $data = array();

    function __construct()
    {
        $this->load->model('select_country_model');
        $this->load->model('common_model');

        $this->data['navigation'] = generate_navigation();  // helper function
        $this->data['country'] = code2country();  // helper function
        $this->data['langs'] = $this->select_country_model->get_langs();

        $query = $this->common_model->get_content('markets', 'architectural');

        foreach ($query as $row) {
            $this->data['title'] = $row->page_title;
            $this->data['description'] = $row->description;
            $this->data['keywords'] = $row->keywords;
        }
    }
}

Then just extend you controller with MY_Controller and you will have access to the $data with $this->data.

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

2 Comments

So I would do $this->load->view('whatever', $this->data)?
I just updated some of my code. Whenever you want to use $data you'll have to reference it with $this->data. That goes for the main controller and all controllers that are extended with it.

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.