将$ data从模型传递到控制器,从控制器传递到视图

时间:2015-03-10 04:19:02

标签: php codeigniter

我的模型中有一个数组($ data)。我想将它传递给我的控制器,因此控制器可以将它传递给视图。

型号:

$data['table'] = $db->get_custom_db($target)->list_tables(); 
return $data;

控制器:

$this->load->view('page', $data);

查看:

var_dump($data); // This returns NULL

我该怎么做?

修改 这是完整代码

控制器

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

class Home extends CI_Controller {

    public function index() {

        $this->load->model('connection_model');
        $db = new Connection_model();

        if (isset($_SESSION['connection'])) {
            if ($db->get_custom_db('sender') && $db->get_custom_db('receiver')) {

                $this->load->model('readdata_model');
                $readData = new ReadData_model();

                $readData->get_table('sender');
                $this->layout->load_template('tables', 'Data Migrator: Overview');
            }
        }
        else {
            // Load the template of Home
            $this->layout->load_template('home', 'Data Migrator: Home');
        }
    }
}

Layout.php(libraries)

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

class Layout {
    protected $ci;

    public function __construct() {
        $this->ci =& get_instance();
    }

    public function load_template($page, $title, $full_template = true, $model = NULL, $model_position = 'top') {
        if (file_exists(APPPATH . 'views/pages/' . $page . '.php')) {
            $data['page_title'] = $title;

            if ($model_position != 'top' && $model_position != 'bottom') {
                exit('Error: Bad parameter (' . $model_position . '). Please use "top" or "bottom" instead.');
            }

            // Building the template
            if ($full_template) {
                $this->ci->load->view('template/header', $data);
                if ($model && $model_position == 'top') {
                    $model;
                }
            }
            $this->ci->load->view('pages/' . $page, $data);
            if ($model && $model_position == 'bottom') {
                $model;
            }
            if ($full_template) {
                $this->ci->load->view('template/footer');
            }
        }
        else {
            show_404();
        }
    }

}

模型

<?php
class ReadData_model extends CI_Model {
    public function get_table($target) {
        if ($target != 'sender' && $target != 'receiver') { exit('Error: Illegal parameter. Please use sender or receiver instead.'); }
        $this->load->model('Connection_model');
        $db = new Connection_model();

        $data['table'] = $db->get_custom_db($target)->list_tables();
        return $data;    
    }
}

查看

<?php
var_dump($table);

1 个答案:

答案 0 :(得分:1)

在您看来,请勿尝试打印$data['index'],而是:$index。这就是Codeigniter的工作方式。

因此,在您的代码中,$table应该可以在视图中访问,而不是$data['table']