声明在Codeigniter中从DB获取值的全局数组

时间:2015-08-28 05:40:00

标签: php codeigniter

我有一个模板可以将我的视图加载到页眉,页脚和main_content等部分。我在页脚中有一个小部件,我想显示特定类别的前5个帖子,比如" Current Affairs"。由于模板是部分加载的,我想要一个加载这些数据并将其提供给模板的footer.php文件的函数。但是,应该在构造函数中加载此函数,以便控制器的所有其他函数不需要调用此函数。这是我的代码。

class Home extends CI_Controller {

// public $data['latest_current_affairs'] = array(); // Tried this, doesnt work.

function __construct()
{
    parent::__construct();
    $this->load->model('Add');
    $this->load->model('Fetch');
    $this->load->library('form_validation');
    $this->load->helper('date');
    // $this->load_widgets(); //works fine if we print an array
}

public function load_widgets()
{
    $where = array('post_category' => "Current Affairs", 'post_status' => "Published");
    $orderby = NULL;
    $limit = 5;
    $data['latest_current_affairs'] = $this->Fetch->selectWhereLimit('post', $where, $orderby, $limit);     
    // print_r($data); //works fine if printed through here.
}

public function index()
{
    $data['main_content'] = 'home';
    $this->load_widgets();
    $this->load->view('includes/template', $data);
    print_r($data); //Here the data prints only the main_content index but not the latest_current_affairs index of the array.
}}

这是我的template.php的内容:

<?php $this->load->view('includes/header'); ?>

<?php $this->load->view($main_content); ?>

<?php $this->load->view('includes/footer'); ?>

欢迎任何有关代码优化或更好编码技术的建议。

2 个答案:

答案 0 :(得分:1)

要在codeigniter中声明globe数组,您必须在config file

中定义
$config['item_name']= array('post_category' => "Current Affairs", 'post_status' => "Published");

用于获取配置项

$this->config->item('item_name');

所以你的索引函数是

public function index()
{
    $where=$this->config->item('item_name');
    $orderby = NULL;
    $limit = 5;
    $data['latest_current_affairs'] = $this->Fetch->selectWhereLimit('post', $where, $orderby, $limit);    
    $data['main_content'] = 'home';
    $this->load->view('includes/template', $data);
    print_r($data); //Here the data prints only the main_content index but not the latest_current_affairs index of the array.
}

<强>已更新

您可以为它创建帮助文件

function load_widgets() 
{ 
$CI = get_instance(); 
$CI->load->model('Fetch'); 
$where=$CI->config->item('item_name'); 
$orderby = NULL; 
$limit = 5; 
return $latest_current_affairs = $CI->Fetch->selectWhereLimit('post', $where, $orderby, $limit); 
}

你控制器

function __construct() 
{ 
parent::__construct(); 
$this->load->model('Add'); 
$this->load->model('Fetch'); 
$this->load->library('form_validation'); 
$this->load->helper('date'); 
$result=$this->load_widgets(); 
print_r($result); 
}

不要忘记给你的帮助文件打电话

答案 1 :(得分:1)

以下示例代码将数据存储在全局数组中。

class Check extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->data['f1'] = $this->f1();
    }

    function f1()
    {
       return "response1";
    }

    function f2()
    {
       $this->data['f2'] = "response2";
       print_r($this->data);
    }
}