duanjin9035 2019-04-07 07:46
浏览 33
已采纳

Codeigniter 3:我怎样才能避免在控制器中重复这段代码?

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?

  • 写回答

1条回答 默认 最新

  • dqzg62440 2019-04-07 14:39
    关注

    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

    e.g:

    // 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?