简体   繁体   中英

Codeigniter 3: how can I avoid repeating this chunk of code in my controllers?

I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.

Several entities are present in all controllers (except Login.php and Register.php): static data, categories and pages.

$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();

Further more, in most controller, the code above appears more then one time.

I am afraid this is mot the only case of repetitive code in the application. (See the entire application, at its current state, on my Github account ).

I am looking for specific and/or general advice from experienced PHP developers that would help me reduce code redundancy and make it more efficient.

What is the best way to avoid the repeating of the code above in my controllers?

In CodeIgniter You can create a core controller in the following path:

application/core/MY_Controller.php

Then you can use it to extend your controllers for example:

class MY_Controller extends CI_Controller {
    public function __construct() {
         // your logic here
    }
}

class Pages extends MY_Controller {
    public function index() {
          // display all pages here
    }
}

You don't have to create the constructor in every class you make unless you need or override something, And if you want to have global data just create a protected property in your core controller & use it in other classes

eg:

// MY_Controller
protected $data;

public function __construct() {
    $this->data = $this->somemodel->get_static()
}

in your controllers you can do something like this

public function index() {
   $this->data['pages'] = $this->pagesmodel->get_pages();
   $this->load->view('path/to/view', $this->data);
}

The core controller is automatically loaded if exists, just create the file & start using it.

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