在CodeIgniter中,我的项目通常有许多固有的脚本,例如:
<?php
// Load many things
$this->load->model('news_model');
$this->load->helper('utility_helper');
$news = $this->news_model->get_basic_news();
// For moment no news
$view_datas['news']['check'] = false;
if ($news) {
$view_datas['news'] = array(
'check' => true,
'news' => _humanize_news($news)
);
}
?>
此脚本用于不同的控制器,目前我创建了一个scripts
文件夹,我将其导入:include(APPPATH . 'scripts/last_news.php');
我很确定这不是解决此问题的最佳方法。有什么想法?
更新
答案中给出的解决方案是使用helper
或library
。
让我们想象一下我之前代码的重写:
class Scripts {
public function last_news() {
// Load many things to use
$CI =& get_instance();
$CI->load->model('news_model');
$CI->load->model('utility_helper');
$news = $CI->news_model->get_basic_news();
// Avoid the rest of code
}
}
答案 0 :(得分:1)
只需创建一个新库并在任何需要的地方加载该库? e.g。
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Newclass {
public function get_news($limit)
{
//return news
}
}
/* End of file Newsclass.php */
在您的控制器中
$this->load->library('newsclass');
$this->newsclass->get_news($limit);
或者另一个想法是创建辅助函数。