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 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名