Jeremie Ges
Jeremie Ges

Reputation: 2745

Best way for scripts in codeigniter

In CodeIgniter I often have many scripts inherent to my project, for instance:

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

        );
}
?>

This script is used in different controllers, at the moment I create a scripts folder and I import it like that: include(APPPATH . 'scripts/last_news.php'); I'm quite sure it's not the best way to handle this problem. Any thoughts on that?

Update: A solution given in the answers is to use a helper or a library. Let's imagine a rewrite of my previous code:

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
}

}

Upvotes: 1

Views: 1262

Answers (1)

TigerTiger
TigerTiger

Reputation: 10806

Just create a new library and load that library whereever you require? 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 */

In your controllers

$this->load->library('newsclass');
$this->newsclass->get_news($limit);

Or another idea is to create helper functions.

Upvotes: 1

Related Questions