dthyxna3894 2018-04-07 08: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 08: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条)

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库