【问题标题】:Best way for scripts in codeignitercodeigniter 中脚本的最佳方式
【发布时间】:2013-02-06 15:25:47
【问题描述】:

在 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 codeigniter scripting


【解决方案1】:

只需创建一个新库并根据需要加载该库吗? 例如

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

或者另一个想法是创建辅助函数。

【讨论】:

  • 是的,这是一个将所有内容放在scripts 类中的解决方案,但想象一下我有 15/16 个脚本,所以 16 种方法,对于速度执行来说,这是不可行的......
  • 另外一件事,如果我创建类或助手来制作这个,通常我会加载许多模型或助手,所以解决方案是制作一个$CI =&amp; get_instance(); ,所以使用超级对象 CI,这个方式很慢。我使用 Codeigniter 是因为我喜欢更快的执行时间,但我认为我们遇到了这个问题......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
相关资源
最近更新 更多