Goose Goose - 16 days ago 6
PHP Question

Get data from model to every view using OOP and DRY

I have a piece of data I want passed to every view. I am using CodeIgniter 3 and have PHP 7 available to me. The current way I do it is using something like this in every function.

$data['foobar'] = $this->general_model->foobar();
// More code
$this->load->view('homepage', $data);


I'd prefer not to have to call
$data['foobar'] = $this->general_model->foobar();
on every single function.

I've tried many approaches to fix this without resorting to anything that makes the code too goofy. I've tried constructors, autoload, and hooks. The problem in each case boils down to the fact that
$data
is local to each function. The best I've gotten is usually something like this.

$data['foobar'] = $this->foobar;
// More code
$this->load->view('homepage', $data);


This is slightly nicer, but it still results in me placing this line in every function.

I'd like my functions to in someway inherit
$data
with the index
foobar
already set. I'd prefer to avoid a solution that requires every function receiving
$data
as a parameter. How can I accomplish this?

Answer

Option 1: Not sure if you have tried this but you could set $data as a property of your class

protected $data = [];

Then in your constructor set it.

$this->data['foobar'] = $this->general_model->foobar();

This would mean your $data becomes accessible to all your methods in your controller and you would need to refer to them as $this->data['data_name'] and use it in a view like

$this->load->view('homepage', $this->data);

Option 2: A second way is to create a method like render() which is common to all your methods that load views and replaces your existing view calls.

So you would have something like...

  public function one_of_my_methods(){
        $data['content'] = 'This is content 1';
        $this->render('test_view',$data); // Call the new view handler
    }

    // All methods using views now call this to load the final view
    public function render($view,$data){
        $data['foobar'] = 'I am common'; // DRY
        $this->load->view($view, $data);
    }
Comments