dthyxna3894 2018-04-07 00:45
浏览 42
已采纳

Codeigniter 3博客应用程序:如何避免静态数据的冗余?

I am working on a blog application in Codeigniter 3.1.8.

I have a model with "static" data like the website's title, the contact email address, etc:

class Static_model extends CI_Model {
    public function get_static_data() {
        $data['site_title'] = "My Blog";
        $data['tagline'] = "A simple blog application made with Codeigniter 3";
        $data['company_name'] = "My Company";
        $data['company_email'] = "company@domain.com";
        return $data;
    }
}

In my Posts Controller, which handles both the posts page and the single post page, I was forced to load the Static_model twice:

class Posts extends CI_Controller {

    public function index()
    {
        $this->load->model('Static_model');
        $data = $this->Static_model->get_static_data();

        $this->load->model('Posts_model');
        $data['posts'] = $this->Posts_model->get_posts();

        $this->load->view('partials/header', $data);
        $this->load->view('posts');
        $this->load->view('partials/footer');
    }

    public function post($id) {
        $this->load->model('Static_model');
        $data = $this->Static_model->get_static_data();

        $this->load->model('Posts_model');
        $data['post'] = $this->Posts_model->get_post($id);

        // Overwrite the default tagline with the post title
        $data['tagline'] = $data['post']->title;

        $this->load->view('partials/header', $data);
        $this->load->view('post');
        $this->load->view('partials/footer');
    }

}

As you can see, the header and footer partials ware also loaded redundantly.

Questions:

  1. How can I load the Static_model only once and so that both the index() and post() methods can use it?
  2. Also, how can I load the partials only once per controller?

Thanks!

展开全部

  • 写回答

2条回答 默认 最新

  • douao2019 2018-04-07 00:58
    关注

    You can load the model in the constructor:

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Static_model');
    }
    

    Since the constructor gets called every time the class is instantiated, it will always be available to any methods called later.

    Regarding the views, you can use require() or include() as usual to load partials from the view file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部