我正在使用Codeigniter 3.1.8中的博客应用。
我的模型包含“静态”数据,如网站标题,联系电子邮件地址等:
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;
}
}
在我的帖子控制器中,它处理帖子页面和单个帖子页面,我被迫加载Static_model 两次:
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');
}
}
如您所见,标题和页脚部分软件也会被冗余加载。
问题:
谢谢!
答案 0 :(得分:0)
您可以在构造函数中加载模型:
public function __construct()
{
parent::__construct();
$this->load->model('Static_model');
}
由于每次实例化类时都会调用构造函数,因此它将始终可用于稍后调用的任何方法。
关于视图,您可以像往常一样使用require()
或include()
来加载视图文件中的部分内容。
答案 1 :(得分:0)
我已经设法获得一个控制器配置帽子比最初的那个更接近:
class Posts extends CI_Controller {
public function __construct()
{
parent::__construct();
// Load static data
$this->load->model('Static_model');
$data = $this->Static_model->get_static_data();
// Load Header
$this->load->view('partials/header', $data);
}
public function index()
{
$this->load->model('Posts_model');
$data['posts'] = $this->Posts_model->get_posts();
$this->load->view('posts', $data);
$this->load->view('partials/footer');
}
public function post($id)
{
$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('post', $data);
$this->load->view('partials/footer');
}
}
$this->load->view('partials/footer');
行仍出现在两个函数中,但我更接近尊重DRY原则。
控制器的这种配置解决了一个问题并创建了另一个问题:行$data['tagline'] = $data['post']->title;
现在没有效果。