CodeIgniter 3博客应用:如何避免静态数据冗余?
Great question—redundant code and repeated data fetching is a common pain point in CodeIgniter, especially when dealing with global static data like site settings. Here are a few clean, CI 3.1.8-friendly solutions to eliminate this redundancy:
1. Use a Core Parent Controller (MY_Controller)
This is the most widely recommended approach in CodeIgniter for sharing global data across multiple controllers. You’ll create a base controller that all your other controllers inherit from, handling the static data load once.
Step 1: Create the Core Controller
Create application/core/MY_Controller.php (CI automatically loads files named MY_* in the core folder):
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller { protected $data = []; public function __construct() { parent::__construct(); // Load the Static_model once here $this->load->model('Static_model'); // Merge static data into the shared $data array $this->data = array_merge($this->data, $this->Static_model->get_static_data()); } }
Step 2: Update Your Posts Controller
Now have your Posts controller inherit from MY_Controller instead of the default CI_Controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Posts extends MY_Controller { public function __construct() { parent::__construct(); // Any additional setup for Posts goes here $this->load->model('Posts_model'); // Example model for posts } // Article list page public function index() { // Add post-specific data to the shared $data array $this->data['posts'] = $this->Posts_model->get_all_posts(); // Pass all data (static + posts) to the view $this->load->view('posts/list', $this->data); } // Single article page public function view($slug) { $this->data['post'] = $this->Posts_model->get_post_by_slug($slug); if (!$this->data['post']) { show_404(); } $this->load->view('posts/single', $this->data); } }
Now your static data (site_title, tagline, etc.) is automatically available in every view loaded via controllers that inherit from MY_Controller—no need to call Static_model in every controller method.
2. Use CodeIgniter Hooks for Global Data
If you want static data to be available across your entire application without relying on controller inheritance, you can use CI’s Hooks system.
Step 1: Enable Hooks
Open application/config/config.php and set:
$config['enable_hooks'] = TRUE;
Step 2: Define the Hook
Open application/config/hooks.php and add this hook (it runs right after the controller is initialized):
$hook['post_controller_constructor'] = [ 'class' => '', 'function' => 'load_static_data', 'filename' => 'static_data_hook.php', 'filepath' => 'hooks', 'params' => [] ];
Step 3: Create the Hook File
Create application/hooks/static_data_hook.php:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); function load_static_data() { $CI =& get_instance(); // Get the CI super instance $CI->load->model('Static_model'); $static_data = $CI->Static_model->get_static_data(); // Make the data available globally in views and controllers foreach ($static_data as $key => $value) { $CI->data[$key] = $value; // Alternatively, assign directly to the view parser $CI->load->vars($static_data); } }
With this setup, your static data is automatically loaded on every request, accessible in any view without passing it explicitly, and available in controllers via $this->data.
3. Cache the Static Data
Since your static data rarely changes, caching it will reduce unnecessary model calls entirely. You can use CodeIgniter’s built-in caching library:
Update Your Static_model
Modify the get_static_data() method to check for a cache first:
class Static_model extends CI_Model { public function get_static_data() { // Check if cache exists $cached_data = $this->cache->get('static_site_data'); if ($cached_data) { return $cached_data; } // If no cache, fetch the 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"; // Cache the data for 7 days (adjust as needed) $this->cache->save('static_site_data', $data, 604800); return $data; } }
Enable Caching
Make sure caching is enabled in application/config/config.php—you can use file-based caching (default) or other drivers like Redis:
$config['cache_driver'] = 'file'; $config['cache_path'] = APPPATH . 'cache/';
This way, the model only fetches and processes the static data once every 7 days, and subsequent calls pull from the cache.
内容的提问来源于stack exchange,提问作者Razvan Zamfir

