У меня есть шаблон, который загружает мой взгляд на части, такие как header, footer и main_content. У меня есть виджет в нижнем колонтитуле, где я бы хотел отобразить 5 лучших постов определенной категории, например "Текущие дела". Поскольку шаблон загружается по частям, мне нужна функция, которая загружает эти данные и передает их в файл 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.
}}
Здесь содержимое моего шаблона.php:
<?php $this->load->view('includes/header'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer'); ?>
Любые предложения по оптимизации кода или лучшим методам кодирования приветствуются.
Вот пример кода Чтобы хранить данные в глобальном массиве.
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);
}
}
Чтобы объявить массив шаров в codeigniter, вы должны определить в своем 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);
}
ans не забудьте вызвать ваш вспомогательный файл