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.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog