开发者

codeigniter where to process sql result?

class SelectedModel extends CI_Model {

    var $title   = 'SelectedModel';
    var $content = 'get top n articles';
    var $date    = '23.2.2011';

    function __construct()
    {
        parent::__construct();
    }

    function getTopArticles()
    {
       $result = $this->db->query('select top 5 article from articles;');
       if( ! $result->num_rows() > 0 )
           die('There are no articles in db.');

       return $result;
    }
}


class Front extends CI_Controller {

    function __construct()
    {
        parent::__construct();
    }

    fun开发者_Go百科ction index()
    {
        $this->load->database();
        $this->load->helper(array('text', 'html'));
        $this->load->model('SelectedModel');

        // controller process data and validate it
        $top_articles = $this->SelectedModel->getTopArticles();
        foreach($top_articles->result() as $item)
        {
            $item->desc = character_limiter($item->desc, 75);
            if( strlen($item->image) == 0 )
                $item->desc = '/images/default.png'; 
        }


        $data['title'] = 'title';
        $data['random_articles'] = $top_articles;
        $this->load->view('front', $data);
    }
}

Front View:

php foreach($random_articles->result() as $item):
    php echo $item->desc
    php echo br() . $item->image
php endforeach;

I'm wondering if my knowledge of MVC is correct. In controller I process data, prepare them to show them in view. In view there is room only for html/css code and echo $var.. Model function is to get data.

Are there any other approaches to process data. Is my way ok?

Optimization issue: $top_articles = $this->SelectedModel->getTopArticles(); I don't know exactly how php manages this line. I'm just asking if $top_articles is a copy of getTopArticles, so I use twice as many memory if i would use in my view:

Front View:

php foreach($random_articles->result() as $item):
    php echo character_limiter($item->desc, 75)
    php echo br() . if( strlen($item->image) == 0 ) echo images/default.png''; else echo $item->image;
php endforeach;

But with this approach I don't use MVC(using character_limit, .... in view).


I think you got the idea down. The MVC approach doesn't always mean its better optimized.

Generating data in a model, passing it to the controller, and then to the view is the correct way to do this, even though it would seem as though you could just do it all from the view with just as many lines of code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜