繁体   English   中英

在Codeigniter中编写脚本的最佳方法

[英]Best way for scripts in codeigniter

在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'); 我很确定这不是解决此问题的最佳方法。 有什么想法吗?

更新:答案中给出的解决方案是使用helperlibrary 让我们想象一下我以前的代码的重写:

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
}

}

只需创建一个新库并在需要的地方加载该库? 例如

<?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);

或者另一个想法是创建助手功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM