mercredi 16 novembre 2016

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?

Aucun commentaire:

Enregistrer un commentaire