我正在尝试使用Fragment帮助程序类优化我的Kohana(3.2.2)应用程序,并且意识到我做错了。
Model_Article:
public function get_articles()
{
/*
* This is just a PDO wrapper, I don't like the kohana built in
* database module
*/
$db = DB::instance();
$article_stmt = $db->prepare("SELECT * FROM articles");
$article_stmt->execute();
return $article_stmt->fetchAll();
}
Controller_Article:
public function action_index()
{
$this->template->content = View::factory('welcome/index');
$this->template->content->articles = Model::factory('article')->get_articles();
}
观点:
<?php if ( ! Fragment::load('home.articles')): ?>
<!-- cache test -->
<?php foreach($articles as $article) echo $article->title . PHP_EOL ?>
<?php Fragment::save(); ?>
<?php endif; ?>
您可以看到,无论视图中发生了什么,查询始终都会执行。我希望在缓存更新时执行查询。但是将模型对象传递给视图会打破一些MVC会话吗?有人可以告诉我该怎么做吗?!
答案 0 :(得分:1)
缓存处理是控制器应该做的事情,而不是视图。
将它从视图移动到控制器并感到高兴。我没有使用Fragment模块,但我想你会明白主要观点:
public function action_index()
{
$this->template->content = View::factory('welcome/index');
if ( ! $articles = Fragment::load('home.articles') )
{
// It's better to use separate view for articles list
$articles = View::factory('articles/list', array('articles' => Model::factory('article')->get_articles());
// Hope not just an output can be captured but argument can also be passed to the save() method of the module
Fragment::save($articles);
}
$this->template->content->articles = $articles;
}
答案 1 :(得分:0)
您必须在视图中进行查询(如果扩展Controller_Template
)或在控制器中回显(如果扩展Controller
)。
实施例
Controller_Article(扩展控制器):
public function action_index()
{
if ( ! Fragment::load('home.articles')):
$template = View::factory('my_template_view');
$template->content = View::factory('welcome/index');
$template->content->articles = Model::factory('article')->get_articles();
echo $template->render(); // If you won't print anything,
// don't use fragments
Fragment::save(); // Save the OUTPUT, but DOES NOT save variables
endif;
}
Controller_article(扩展Controller_Template ):
public function action_index()
{
$this->template->content = View::factory('welcome/index');
}
查看(欢迎/索引):
<?php
// echo $articles; // Now Controller is not binding this variable
if ( ! Fragment::load('home.articles')):
// Variable - Does NOT save in Fragment
$articles = Model::factory('article')->get_articles();
// ECHO = save to Fragment
foreach($articles as $article) echo $article->title . PHP_EOL;
Fragment::save(); // Save the OUTPUT, but DOES NOT save variables
endif;
?>
如果您想保存变量,请使用Kohana Cache。