在CodeIgniter中正确扩展

时间:2014-05-14 23:08:50

标签: php codeigniter codeigniter-2

我有一个模板,我需要加载某些信息,并且只想这样做一次所以我必须创建一个名为MY_Controller的扩展控制器。 但是我坚持将MY_Controller中的$ data数组扩展到其他控制器。

这是MY_Controller.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class MY_Controller extends CI_Controller
    {
        public $layout;
        public $id;

        public function __construct()
        {
            parent::__construct();

            $this->output->nocache();

            $this->load->model('subject_model');
            $this->load->model('user_model');
            $this->load->model('survey_model');

            // This is the info I need for every controller and method in my app
            $data['total_subjects'] = $this->subject_model->countSubjects();
            $data['check_if_already_posted_it_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('it_survey', $this->id);
            $data['total_users'] = $this->user_model->countUsers();
            $data['subjects'] = $this->subject_model->get_all_subjects();
            $data['schools'] = $this->subject_model->get_all_schools();
            $data['subject_name'] = $this->subject_model->getSubjectNameById($this->id);
            $data['school_name'] = $this->subject_model->getSchoolNameById($this->id);

            $this->id = $this->session->userdata('user_id');
            $this->layout = 'layout/dashboard';
        }
    }
?>

这当然给了我一个错误。如果不重复自己并在每个方法中加载相同的数据数组,我该怎么做才能让这个工作正常工作,因为到目前为止,这是我让它无故障地工作的唯一方法。

1 个答案:

答案 0 :(得分:1)

如果要从其他控制器访问$data数组,则必须将其设置为属性

class MY_Controller extends CI_Controller
{
    public $layout;
    public $id;
    public $data = array();

    public function __construct()
    {
        parent::__construct();

        $this->output->nocache();

        $this->load->model('subject_model');
        $this->load->model('user_model');
        $this->load->model('survey_model');

        // This is the info I need for every controller and method in my app
        $data['total_subjects'] = $this->subject_model->countSubjects();
        $data['check_if_already_posted_it_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('it_survey', $this->id);
        $data['total_users'] = $this->user_model->countUsers();
        $data['subjects'] = $this->subject_model->get_all_subjects();
        $data['schools'] = $this->subject_model->get_all_schools();
        $data['subject_name'] = $this->subject_model->getSubjectNameById($this->id);
        $data['school_name'] = $this->subject_model->getSchoolNameById($this->id);

        $this->data = $data;

        $this->id = $this->session->userdata('user_id');
        $this->layout = 'layout/dashboard';
    }
}

如果您使用的是所有php代码 remove your php end tag

,还有一个建议