duanjin9035 2019-04-06 23: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 06: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.

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部