【发布时间】:2011-07-02 16:59:13
【问题描述】:
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();
}
function 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);
}
}
前视图:
php foreach($random_articles->result() as $item):
php echo $item->desc
php echo br() . $item->image
php endforeach;
我想知道我对 MVC 的了解是否正确。在控制器中我处理数据,准备它们以在视图中显示它们。在视图中,只有 html/css 代码和 echo $var.. 模型功能是获取数据。
还有其他处理数据的方法吗?我的方法好吗?
优化问题: $top_articles = $this->SelectedModel->getTopArticles(); 我不确切知道 php 是如何管理这条线的。我只是在问 $top_articles 是否是 getTopArticles 的副本,所以如果我想使用的话,我会使用两倍的内存:
前视图:
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;
但是通过这种方法,我不使用 MVC(使用 character_limit, .... in view)。
【问题讨论】:
-
你有很多代码和几个关于它的声明。但我似乎无法确定您实际上在问什么?
-
我在询问您在哪个控制器、模型、视图中处理/验证数据。当我得到答案时,您在控制器中处理/验证数据并将其传递给查看。您在模型中生成数据。
标签: php sql codeigniter